选择查询以连接两个表?

时间:2013-08-13 18:15:11

标签: mysql sql

tableone: id | userid | date | photo | caption | visible
tabletwo: id | userid | date | text  | gender  | notes

我有两个不同列的表。我想使用单个查询从两者中选择行,我会使用日期(时间戳)和用户ID来执行此操作。是否可以将它们连接在一起?

SELECT id, photo, caption, visible
FROM `tableone`
WHERE `userid` = $user->id AND `date` = '$d'
ORDER BY date desc

SELECT id, text, gender, notes
FROM `tabletwo`
WHERE `userid` = $user->id AND `date` = '$d'
ORDER BY date desc
LIMIT 1

编辑:期望的输出:

(
    [id] => 3
    [photo] => 1
    [caption] => Sample text
    [visible] => 1
    [text] => 
    [gender] => 
    [notes] => 
)
(
    [id] => 23
    [photo] => 1
    [caption] => More sample text
    [visible] => 
    [text] => 
    [gender] => 
    [notes] => 
)
(
    [id] => 1
    [photo] => 
    [caption] => 
    [visible] => 
    [text] => Blah jaspidj
    [gender] => 2
    [notes] => Sample Text
)

2 个答案:

答案 0 :(得分:2)

所以你可以得到两个表行数据都有用户ID和日期像param一样? 好的,必须使用JOIN将它们全部放在一行

SELECT t1.id, t1.userid, t1.date, t1.photo, t1.caption, t1.visible, t2.text, t2.gender, t2.notes
FROM tableone t1 JOIN tableone t2 ON t1.ID = t2.ID
WHERE t1.userid = "yourwantedid" AND t1.date = "yourwanteddate"

您只能在WHERE子句中使用表1,因为您将两个表连接在一起。

抱歉我的英语不好。希望这个帮助

我最近看到你的评论,可能你想使用UNION ALL子句

SELECT t1.id, t1.userid, t1.date, t1.photo, t1.caption, t1.visible
FROM tableone t1
WHERE userid = "yourwantedid" AND date = "yourwanteddate"
UNION ALL
SELECT t2.id, t2.userid, t2.date, t2.text as photo, t2.gender as caption, t2.notes as visible
FROM tabletwo t2
WHERE userid = "yourwantedid" AND date = "yourwanteddate"

您必须在列上添加别名以使用UNION ALL子句,该子句与两个选择的列名称匹配。

抱歉我的英语不好。希望这个帮助

答案 1 :(得分:2)

您正在寻找的概念是UNION(请参阅MySql UNION reference),它将两个查询的结果组合在一起。通常,您只联合具有相同列的结果,但是您要求联合两种不同类型的查询。如果您关心的是所有结果并且您不关心空白单元格,那么这应该对您有用:

(SELECT id, photo, caption, visible, null AS text, null AS gender, null AS notes
FROM `tableone`
WHERE `userid` = $user->id AND `date` = '$d'
ORDER BY date desc)
UNION ALL
(SELECT id, null AS photo, null AS caption, null AS visible, text, gender, notes
FROM `tabletwo`
WHERE `userid` = $user->id AND `date` = '$d'
ORDER BY date desc
LIMIT 1)

(请注意,我使用了UNION ALL代替UNION,这基本上意味着“给我所有结果,包括重复”。由于此套装中无法重复,因此安全使用UNION ALL来提升效果

这个输出在逻辑上没有意义,但它应该给你上面显示的示例输出。