简体   繁体   English

mysql获取不存在的结果

[英]mysql get non existing results

Using php and mysql, 使用php和mysql,
I have a table "subdomains" that contains subdomains for my application, depending of a category. 我有一个表“ subdomains”,其中包含我的应用程序的子域,具体取决于类别。 subdomains - id, cat_id, subdomain 子域-ID,CAT_ID,子域

Some categories have subdomain and others don't have. 有些类别有子域,有些则没有。 For those that don't have subdomain, I want the subdomain to be 'www'. 对于那些没有子域的用户,我希望该子域为“ www”。

Now in my subdomains table there are a few values, for example : 现在在我的子域表中有一些值,例如:

subdomains : id, cat_id, subdomain
             1,  6,   "sales"
             2,  7,   "infos"

Now, I have an array of cat_id, for example $aCatIds = array(1,5,6,8); 现在,我有了一个cat_id数组,例如$ aCatIds = array(1,5,6,8);

At the end of the mysql query I would like a something like this : 在mysql查询的结尾,我想要这样的东西:

array(
0 => (cat_id="1", subdomain="www") ,
1 => (cat_id="5", subdomain="www") ,
2 => (cat_id="6", subdomain="sales") ,
3 => (cat_id="8", subdomain="www") ,
)

Is it possible with only one mysql query ? 是否只有一个mysql查询可能吗?

I use php and tried things like this : 我使用php并尝试了以下操作:

$stmt = "select cat_id, ifnull('www', subdomain) as subdomain
    from subdomains
    where cat_id in (". implode(',', $aCatIds) .")";

But I only get the values that are set (6 in the above example), and I don't know how to tell mysql to get the expected array. 但是我只得到设置的值(在上面的示例中为6),并且我不知道如何告诉mysql获取期望的数组。

To make this work, you'll have to (left) join to existing data (where the cat_id does exist). 要使此工作有效,您必须(左)加入现有数据(cat_id确实存在的地方)。 For instance, if I assume a cat table exists which the cat_id references, 't would be so: 例如,如果我假设存在一个cat_id引用的cat表,则“ t”将是这样:

SELECT c.id as cat_id,IFNULL(s.subdomain,'www')
FROM cat c 
LEFT JOIN subdomains s
ON s.cat_id = c.id
WHERE c.id IN (1,2,3,4);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM