Mysql

是否可以加入這兩個表?

  • March 15, 2021
SELECT u.*,h.*,d.* 
FROM User u
LEFT JOIN HealthDec h ON u.ID = h.EmpId
LEFT JOIN Document d On u.ID = d.UserID;

和:

SELECT count(id) FROM OHS 
WHERE Category = 'POLICIES' 
 AND ID NOT IN 
 (
   SELECT OHSID 
   FROM User_OHS 
   WHERE UserID='1' AND Type='POLICIES'
 );

兩個查詢都可以根據需要分別正常工作。但我想結合這兩個查詢來為每個使用者獲取結果。

表結構

你可以像這樣組合它們,只要你的 subse3lect 只有 onbe 行和 1 個 coumn

SELECT u.*,h.*,d.* ,
(SELECT count(id) FROM OHS 
WHERE Category = 'POLICIES' 
 AND ID NOT IN 
 (
   SELECT OHSID 
   FROM User_OHS 
   WHERE UserID=u.ID AND Type='POLICIES'
 )) as countr
FROM User u
LEFT JOIN HealthDec h ON u.ID = h.EmpId
LEFT JOIN Document d On u.ID = d.UserID;

User_OHS 是“多對多映射”或“橋接”表。這是數據庫中的常見模式。

SELECT u.this, o.that, ...
   FROM User     AS u
   JOIN User_OHS AS uo  ON uo.UserID = u.ID
   JOIN      OHS AS  o  ON uo.OHSID = o.ID
   WHERE ...

但它的索引通常很差。建議:http: //mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

TEXT除非列確實可能超過幾百個字元,否則不要使用 Datatype 。什麼HomePhone需要超過 20 個字元?同上uo.Type。此建議有助於在某些查詢中創建有用的索引和性能。

如果您要Birthdate與任何事物進行“比較”,請將其設為DATE,而不是VARCHAR. (並確保在插入值時對其進行清理。)

引用自:https://dba.stackexchange.com/questions/287068