我有两个(或三个或四个......)表,我想一次性选择所有表中的条目数。
例如,如果我有一些表: '新闻','文章','画廊'
在每个表中我有一行称为“author_id”
现在,如果我使用以下select语句:
SELECT *
FROM
news as n, articles as a, galleries as g
WHERE
n.author = 1
AND a.user = 1
AND g.uploader = 1
我只得到一个结果,如果每个表至少有一行与作者(或用户或上传者)匹配'1' 即使一个(或两个......)表不包含'1'
,我怎样才能得到结果答案 0 :(得分:1)
或者,您可以在子查询中使用UNION ALL
组合所有表的结果。然后,您现在可以COUNT()
指定的Author_ID
。以下查询将获取所有表中指定author_id
的记录总数。
SELECT COUNT(author_ID)
FROM
(
SELECT userID AS Author_ID FROM news
UNION ALL
SELECT user_ID AS Author_ID FROM articles
UNION ALL
SELECT UiD AS Author_ID FROM galleries
) a
WHERE a.Author_ID = 1
后续问题,
答案 1 :(得分:0)
你必须使用字段来显示每个表格,如
SELECT n.author, a.user, g.uploader FROM news as n, articles as a, galleries as g
WHERE n.author = 1 AND a.user = 1 AND g.uploader = 1
那么它会起作用
答案 2 :(得分:0)
您的news
表似乎是父表,因此您应该LEFT JOIN
articles
和galleries
表与news
表来计算作者,如下:
SELECT *
FROM
news n
LEFT JOIN articles a
ON n.author_id = a.author_id AND a.user = 1
LEFT JOIN galleries g
ON n.author_id = g.authori_id AND g.uploader = 1