我有三张表activity_log
,user
,staff
。我必须从activity_log
中选择数据,以确定哪个用户已完成哪项活动。
这是activity_log
table
CREATE TABLE `activity_log` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`os` varchar(20) NOT NULL,
`api` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
转储表格activity_log
INSERT INTO `activity_log` (`id`, `user_id`, `os`, `api`) VALUES
(1, 1, 'web', 'user/login'),
(2, 2, 'web', 'user/report'),
(3, 1, 'android', 'user/login'),
(4, 2, 'ios', 'user/data'),
(5, 3, 'android', 'user/category'),
(6, 3, 'web', 'user/result'),
(7, 3, 'ios', 'user/send_sms');
这是user
table
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`first_name` varchar(100) NOT NULL,
`last_name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
转储表格user
INSERT INTO `user` (`id`, `first_name`, `last_name`) VALUES
(1, 'Yogesh', 'Kale'),
(2, 'Sunit', 'Desai'),
(3, 'Paresh', 'Godambe');
这是我的staff
表
CREATE TABLE `staff` (
`id` int(11) NOT NULL,
`first_name` varchar(100) NOT NULL,
`last_name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
转储表格staff
INSERT INTO `staff` (`id`, `first_name`, `last_name`) VALUES
(1, 'abcd', 'asas'),
(2, 'ajay', 'shinde'),
(3, 'kapil', 'parab');
但我必须加入activity
登录一个条件。该条件基于os
表中的activity_log
列。如果os
列的值包含web
,那么我必须加入user_id
activity_log
id
列staff
列的os
列ios
列包含android
或id
的值,然后我必须将activity_log的user_id与user table的id列相关联。
我需要两个不同的查询,用于从api
,activity_log
,first_name
last_name
或{{{}获取staff
和user
列的数据1}}和另一个用于获得相同上述条件的总count
。我已经提供了我的表模式供参考。
我尝试过以下查询来获取数据
SELECT
al.id as id,
CONCAT(u.first_name, ' ', u.last_name) as user_name,
al.api
FROM
activity_log al
JOIN
user u
ON
u.id = al.user_id
WHERE
al.os IN('android','os')
UNION ALL
SELECT
al.id as id,
CONCAT(st.first_name, ' ', st.last_name) as user_name,
al.api
FROM
activity_log al
JOIN
staff st
ON
st.id = al.user_id
WHERE
al.os = 'web'
以上查询返回正确的数据。但我不知道如何计算上述条件。多数民众赞成在我坚持这一点。如果可能的话,请给我一些关于获取数据和计数的替代查询。
请帮帮我。我花了一整天才弄明白这一点。提前致谢
答案 0 :(得分:0)
您可以尝试使用UNION ALL
获取所需数据。
查询1:
select al.id, al.api,s.first_name, s.last_name from activity_log al inner join staff s on al.user_id=s.id where al.os='web'
UNION ALL
select al.id, al.api,u.first_name, u.last_name from activity_log al inner join user u on al.user_id=u.id where al.os!='web'
查询2:
select
(select count(*) from activity_log al, staff s where al.user_id=s.id and al.os='web') as webcount,
(select count(*) from activity_log al, user u where al.user_id=u.id and al.os!='web') as othercount
我希望这可以为你的问题指明方向。
答案 1 :(得分:0)
尝试
SELECT ...,count(*) FROM table1
INNER JOIN table2 ON ... WHERE ...