【问题标题】:Result for a particular user特定用户的结果
【发布时间】:2023-02-21 17:19:13
【问题描述】:

我想显示特定用户的结果以及所有项目的列表以及用户是否订购该项目的信息。

我有 3 个表,帐户 (t1)、项目 (t2) 和包含 item_id、item_name、stat、shipped 的 t3。

表格1

CREATE TABLE table1(
    id NOT NULL AUTO_INCREMENT,
    user_name varchar(255),
);

表 2

CREATE TABLE table2(
    id NOT NULL AUTO_INCREMENT,
    item_name varchar(255),
);

表3

CREATE TABLE table3 (
  id int NOT NULL AUTO_INCREMENT,
  user_id int NOT NULL,
  item_id int NOT NULL,
  stat tinyint NOT NULL,
  shipped tinyint NOT NULL,
  PRIMARY KEY (id),
  FOREIGN KEY (user_id) REFERENCES table1(id),
  FOREIGN KEY (item_id) REFERENCES table2(id)
);

上次我获得有关 JOIN 的帮助,但它没有显示特定用户的所有 item_id 和 item_name。应该是这样的https://pastebin.com/XNCAEGtp

SELECT 
    t2.item_id,
    t2.item_name,
    t3.stat,
    t3.shipped
    t1.user_name,
FROM table2 t2
    LEFT JOIN table3 t3 ON t2.id = t3.item_id
    LEFT JOIN table1 t1 ON t3.user_id = t1.userid

谢谢你!

【问题讨论】:

  • pastebin 链接没有显示用户,但您的查询没有 where 子句来“显示特定用户的结果”,这有点令人困惑
  • 我的 php 脚本需要 user_id。所有这些都将显示在 <table> 标记中,除了 user_id

标签: mysql sql


【解决方案1】:

要建立用户可能已经订购的项目,您需要将用户交叉连接到项目,然后要建立他们实际订购的项目,您需要左连接。为了清楚起见,第一部分的 cte 会很有用。例如

with cte as
(select user_id from a cross join b)
select distinct cte.user_id,c.item,
       case when shipped = 1 then 1 else 0 end as shipped
from cte 
left join c on c.user_id = cte.user_id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2011-08-13
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    相关资源
    最近更新 更多