如何使用WHERE CLAUSE和ORDER BY进行SQL LEFT JOIN?说明中的详细信息

时间:2018-03-26 23:19:23

标签: sql sqlite

我正在制作一个显示广告记录及其交易的程序。

我有这3个表customer_tbmediaadv_tbcontracts_tb

我在contracts_tb中有外键,主要是来自customer_tbmediaadv_tb的ID引用。

我想在一个表格中显示的内容如下:

contracts_tb.contract_id
    ,contracts_tb.media_idref referrences mediaadv_tb.media_id
    ,contracts_tb.customer_idref referrences customer_tb.cus_id
    ,
WHERE contracts_tb.STATUS = "Active" (I want TO show STATUS that are ONLY = "Active")
    ,customer_tb.firstname || ' ' || middlename || ' ' || lastname AS fullname
    ,customer_tb.company
    ,mediaadv_tb.title
    ,mediaadv_tb.previewimg then ordered BY hpd ASCENDING(hours per day which the ads must be played)

这是我的表格的创建语句查询:

CREATE TABLE contracts_tb (
    contract_id INTEGER PRIMARY KEY NOT NULL
    ,customer_idref INTEGER REFERENCES customer_tb(cus_id)
    ,media_idref INTEGER REFERENCES mediaadv_tb(med_id)
    ,STATUS TEXT
    ,hpd NUMERIC
    ,dateadded DATE
    ,dateexpiration TEXT
    ,amountpaid REAL
    ,arearofcoverage TEXT
    ) WITHOUT ROWID

CREATE TABLE customer_tb (
    cus_id TEXT NOT NULL
    ,company TEXT UNIQUE
    ,firstname TEXT
    ,middlename TEXT
    ,lastname TEXT
    ,gender TEXT
    ,dob DATE
    ,dateregistered DATE
    ,contactno TEXT
    ,emailaddress TEXT
    ,description TEXT
    ,cuspic BLOB
    ,PRIMARY KEY (cus_id)
    )

CREATE TABLE mediaadv_tb (
    med_id TEXT NOT NULL
    ,type TEXT
    ,title TEXT
    ,duration NUMERIC
    ,dateadded TEXT
    ,filepath TEXT
    ,previewimg BLOB
    ,PRIMARY KEY (med_id)
    );

感谢您的考虑!

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT a.firstname || ' ' || a.middlename || ' ' || a.lastname AS fullname,
       a.company,
       c.title,
       c.previewimg
  FROM customer_tb a
  LEFT OUTER JOIN contracts_tb b
    ON b.customer_idref = a.cus_id
  LEFT OUTER JOIN mediaadv_tb c
    ON c.med_id = b.media_idref
 WHERE b.status = 'Active'
 ORDER BY b.hpd