MySQL if 语句条件连接

发布于 2024-12-08 10:21:57 字数 1431 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一绘本一梦想 2024-12-15 10:21:57

怎么样:

SELECT * 
from accounttable
left join peopletable ON (accounttype = 'person' AND peopletable.id = accounttable.person_id)
left join companytable ON (accounttype = 'company' AND companytable.id = accounttable.company_id)

我将连接两个表,这样您将在输出中拥有所有三个表的字段。如果 accounttype != 'person',则 peopletable 中的字段将为 NULL,而 companytable 中的字段将为 < code>NULL 其中 accounttype != 'company'

您可以在 这里...

What about something like:

SELECT * 
from accounttable
left join peopletable ON (accounttype = 'person' AND peopletable.id = accounttable.person_id)
left join companytable ON (accounttype = 'company' AND companytable.id = accounttable.company_id)

I'll join against both tables, so you'll have fields of all three tables in the output. The fields from peopletable will be NULL if accounttype != 'person', and those of companytable will be NULL where accounttype != 'company'.

You can find more on the LEFT JOIN syntax in places like here...

孤寂小茶 2024-12-15 10:21:57
SELECT a.*, p.*, c.* from accounttable a
LEFT JOIN peopletable p ON (a.person_id = p.id AND a.account_type = 'person')
LEFT JOIN companytable c ON (a.company_id = c.id AND a.account_type = 'company')

请注意,a、p、c 是完整表名的别名,这可以节省键入时间。

此查询将为连续的 p.* 或 c.* 提供所有 null
您可以像这样重写选择部分:

SELECT 
  a.id, a.accounttype
  , COALESCE(p.name, c.name) as name
  , COALESCE(p.address, c.address) as address
....
FROM .....

请参阅: http://dev.mysql .com/doc/refman/5.0/en/comparison-operators.html#function_coalesce

SELECT a.*, p.*, c.* from accounttable a
LEFT JOIN peopletable p ON (a.person_id = p.id AND a.account_type = 'person')
LEFT JOIN companytable c ON (a.company_id = c.id AND a.account_type = 'company')

Note that a,p,c are aliases for the full tablenames, this saves on typing.

This query will give all null for either p.* or c.* in a row.
You can rewrite the select part like so:

SELECT 
  a.id, a.accounttype
  , COALESCE(p.name, c.name) as name
  , COALESCE(p.address, c.address) as address
....
FROM .....

See: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce

秉烛思 2024-12-15 10:21:57

它必须像下面这样(据我所知)

SELECT a.*,p.*,c.* 
FROM accounttable a
LEFT JOIN companytable c ON c.id = a.company_id AND a.account_type = 'company'
LEFT JOIN peopletable p ON p.id = a.person_id AND  a.account_type = 'person'

IT MUST BE like below ( as far as i understand )

SELECT a.*,p.*,c.* 
FROM accounttable a
LEFT JOIN companytable c ON c.id = a.company_id AND a.account_type = 'company'
LEFT JOIN peopletable p ON p.id = a.person_id AND  a.account_type = 'person'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文