如何在表中选择在另一个表

时间:2015-06-17 00:17:05

标签: sql sqlite

我有两个SQL表(我正在使用SQLite)。

Table1 (code TEXT)
Table2 (code TEXT, codeTable1 TEXT)

如何获取表2中至少有一行的table1内容,其中codeTable1不为null?

3 个答案:

答案 0 :(得分:0)

select
  a.*
from 
 Table1 a
where
  exists (select * from Table2 b where b.codeTable1 is not null)

select
  a.*
from 
 Table1 a
where
  exists (select * from Table2 b where b.codeTable1 = a.code)

不确定查询的目的。

答案 1 :(得分:0)

我认为你想要一个相关的子查询:

<?php
if($_POST){
    $sql = mysql_query("SELECT * FROM evento");
    while ($evento = mysql_fetch_object($sql)) {
        if($_POST["id".$evento->id_evento] == $evento->id_evento){
            echo "oi";
        }
    }

}else{
    $sql = mysql_query("SELECT * FROM evento");
    while ($evento = mysql_fetch_object($sql)) {

        echo "<form action='eventos' method='POST'>
                <input type='hidden' name='id' value='".$evento->id_evento."'/>
                <div onclick='javascript: this.submit();' id='id' class='col-md-4' >
                    <div style='white-space: nowrap;text-align: center;min-height:190px'>
                        <span style='display: inline-block;height: 100%;vertical-align: middle;'></span><img src='".$root."img/upload/eventos/".$evento->img."' style='width:100%; max-height:200px; vertical-align: middle;'>
                    </div>
                    <p style='color:#00AEC3;background:#F2F2F4;padding:10px 5px'>" . $evento->titulo . "<br> <span style='color:black'>".date('d/m/Y', strtotime($evento->data_inicio))." à ".date('d/m/Y', strtotime($evento->data_fim))."</span></p>
                </div>
            </form>";
    }  
}
?>

这似乎是对您的要求的直接翻译。

答案 2 :(得分:0)

简单的连接应该这样做:

以下是查询:

select 
    *
from
    table1
    join table2 on table1.code = table2.table1_code
where
    table1.code is not null

以下是完整示例:

use example;

drop table if exists table1;
drop table if exists table2;

create table table1 (
    code varchar(64)
);

create table table2 (
    code varchar(64),
    table1_code varchar(64) references table1(code)
);

insert into table1 values('CODE1');
insert into table1 values('CODE2');
insert into table1 values('CODE3');
insert into table1 values('CODE4');
insert into table1 values('CODE5');
insert into table1 values(null);


insert into table2 values('VAL1', 'CODE1');
insert into table2 values('VAL3', 'CODE3');
insert into table2 values('VAL5', 'CODE5');
insert into table2 values(null, null);
insert into table2 values(null, null);
insert into table2 values(null, null);

select 
    *
from
    table1
    join table2 on table1.code = table2.table1_code
where
    table1.code is not null

+ --------- + --------- + ---------------- +
| code      | code      | table1_code      |
+ --------- + --------- + ---------------- +
| CODE1     | VAL1      | CODE1            |
| CODE3     | VAL3      | CODE3            |
| CODE5     | VAL5      | CODE5            |
+ --------- + --------- + ---------------- +
3 rows