0
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
)
4

2 回答 2

2

因此,您可以获得具有用户 ID 和日期(如参数)的两个表行数据?好的,所以必须使用 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 子句,该子句匹配两个选择的列名。

对不起,我的英语不好。希望这有帮助

于 2013-08-13T18:29:48.697 回答
2

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

(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来提高性能是安全的)

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

于 2013-08-13T18:46:34.143 回答