我有几张表我想从我的数据库中获取并将它们组合成一个结果查询。
我有一张products
桌子:
+-----------------+-----------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-----------------------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| menu_id | bigint(20) | YES | | NULL | |
| menu_is_section | int(1) | NO | | 1 | |
| company_id | bigint(20) | NO | MUL | NULL | |
| name | varchar(255) | NO | | NULL | |
| description | mediumtext | YES | | NULL | |
| image | varchar(255) | NO | | NULL | |
| initial_time | datetime | YES | | NULL | |
| final_time | datetime | YES | | NULL | |
| archived | int(1) | NO | | 0 | |
| full_image | varchar(255) | YES | | NULL | |
| kind | enum('PRODUCT','PROMOTION') | NO | | PRODUCT | |
+-----------------+-----------------------------+------+-----+---------+----------------+
一张product_likes
表:
+------------+------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------+------+-----+-------------------+-----------------------------+
| user_id | bigint(20) | NO | MUL | NULL | |
| product_id | bigint(20) | NO | MUL | NULL | |
| liked_on | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+------------+------------+------+-----+-------------------+-----------------------------+
还有一个users
表,其唯一相关字段是id
我想获取菜单下的所有产品并确定用户是否“喜欢”该给定产品。为此,我正在考虑进行连接以创建一个新列,该列将创建包含 1 或 0 的“喜欢”列,以查看用户是否喜欢产品。
但我有点卡住了,因为我找不到用 MySQL 有条件地填充列的方法。
到目前为止,我的查询如下所示:
"SELECT id, name, description, concat('$image_base_url/products/', image) AS icon, concat('$image_base_url/products_full/', full_image) AS full_image FROM (SELECT * FROM products WHERE menu_id = ? AND menu_is_section = ?) AS selected WHERE UTC_TIMESTAMP() BETWEEN initial_time AND final_time ORDER BY initial_time DESC"
而我需要完成的所有事情就是查找 user_id 是否喜欢 product_it,并相应地创建列。
最好的方法是什么?
编辑:
我刚刚做了一个 LEFT JOIN,我想我已经接近我想要的了。“喜欢”返回 1,但我 99% 确定这是因为 user_id 为 1。当用户不喜欢产品时,它返回 NULL。我可以使用它,但如果我的网络服务器返回 1 和 0 会更好。
"SELECT selected.id, u_likes.user_id AS liked, selected.name, selected.description, concat('$image_base_url/products/', selected.image) AS icon, concat('$image_base_url/products_full/', selected.full_image) AS full_image FROM (SELECT * FROM products WHERE menu_id = ? AND menu_is_section = ?) AS selected LEFT JOIN (SELECT * FROM product_likes WHERE user_id = ?) AS u_likes ON selected.id = u_likes.product_id WHERE UTC_TIMESTAMP() BETWEEN selected.initial_time AND selected.final_time ORDER BY selected.initial_time DESC"