我想把两个问题放在一起;一个来自我的posts
表,一个来自我的store_products
表,并在同一页面上显示结果。
所以我想接受这个...
SELECT
p.id AS pid
, p.uid
, p.title
, p.created_at
, u.id AS uid
, u.username
, u.avatar
, f.following
, l.uid AS liked
, u2.username AS source_username
, u2.avatar AS source_avatar
, u2.created_at AS source_created_at
FROM posts p
LEFT JOIN users u ON p.uid=u.id
LEFT JOIN posts_likes l ON l.pid=p.id
LEFT JOIN follow f ON u.id = f.following
LEFT JOIN posts p2 ON p.source_hash = p2.hash
LEFT JOIN users u2 ON u2.id = p2.uid
WHERE (f.user=2 OR p.uid=2)
GROUP BY p.id ORDER BY p.id DESC
并用这样的东西......
SELECT name, price FROM store_products WHERE uid=2
我尝试了多个SELECT
语句,UNION
,我使用NULL
弥补了cols的差异,我尝试了LEFT
,{ {1}}和RIGHT
加入,但所有这些都是将产品信息添加到其他帖子行,而不是为每个产品创建单独的行。
我正在寻找的结果集类似于
INNER
等...
编辑:回答问题。两个表之间的唯一关系是用户ID,否则它们是完全分开的。我想向访问者提供帖子和产品的列表,我试图在一个查询中执行此操作以节省服务器负载,并将它们放在同一列表中而不是单独的列表中。
答案 0 :(得分:0)
使用UNION:
SELECT
"Post" AS type,
, p.id AS pid
, p.uid
, p.title
, p.created_at
, u.id AS uid
, u.username
, u.avatar
, f.following
, l.uid AS liked
, u2.username AS source_username
, u2.avatar AS source_avatar
, u2.created_at AS source_created_at
, NULL AS product_name
, NULL AS price
FROM posts p
LEFT JOIN users u ON p.uid=u.id
LEFT JOIN posts_likes l ON l.pid=p.id
LEFT JOIN follow f ON u.id = f.following
LEFT JOIN posts p2 ON p.source_hash = p2.hash
LEFT JOIN users u2 ON u2.id = p2.uid
WHERE (f.user=2 OR p.uid=2)
GROUP BY p.id
ORDER BY p.id DESC
UNION
SELECT
"Product" AS type
, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
, name, price
FROM store_products
WHERE uid = 2
然后,应用程序代码可以检查type
列,以确定它是否正在打印Post
或Product
,并对其进行适当格式化。