How do I do this?
I have this table:
Table1
|--ID--|--Stars--|--Name--|
| 1 | 3 | Pe |
| 2 | 5 | Me |
| 3 | 7 | Fe |
|------|---------|--------|
Table2
|--ID--|--Teams--|--Age---|--Name--|
| 1 | A | 20 | Pe |
| 2 | A | 20 | Me |
| 3 | A | 20 | Pe |
|------|---------|--------|--------|
I want the sum of stars in Table1 where Name exists in Table2 and Teams=A and Age=20. (3+5=8stars)
I use this, but how do I only count the stars where the name in Table1 matches the name in Table2?
$result = mysql_query("SELECT SUM(Stars) AS starsum FROM Table1 WHERE EXISTS (select * from Table2 WHERE Teams = 'A' AND Age = '20')");
$row = mysql_fetch_assoc($result);
$antalstjernerhold = $row['starsum'];
Try this query
SELECT SUM(t1.Stars) AS starsum
FROM Table1 t1 INNER JOIN Table2 t2
ON t1.Name=t2.Name AND t2.Teams='A' AND t2.Age=20
You have to use inner join to get desired results.
You can write your query this way:
SELECT SUM(Stars) AS starsum
FROM Table1 t1
WHERE
EXISTS (
SELECT *
FROM Table2 t2
WHERE
T2.Name=T1.Name
AND T2.Teams='A'
AND t2.Age=20
)
You can use the following code
$result = mysql_query("
SELECT SUM(Stars) AS starsum
FROM Table1
WHERE Name IN (
SELECT DISTINCT t1.Name
FROM Table1 t1, Table2 t2
WHERE t1.Name = t2.Name
AND t2.Teams = 'A'
AND t2.Age = 20
)
");
$row = mysql_fetch_assoc($result);
$antalstjernerhold = $row['starsum'];
The query is using below subquery which will fetch the names belonging to both tables and have teams as A and Age 20 & then using those names we get the sum of stars
SELECT DISTINCT t1.Name
FROM Table1 t1, Table2 t2
WHERE t1.Name = t2.Name
AND t2.Teams = 'A'
AND t2.Age = 20
Related
Example Table Structure
Table 1
ID | Name | Price
-----------------------------
1 | Casio | 30
2 | Titan | 40
Table 2
ID | Place | Price
-----------------------------
1 | Cali | 30
2 | Mexi | 10
Operation to perform:
Table1(Price) - Table2(Price) for ID = 1
New Table 1
ID | Name | Price
-----------------------------
1 | Casio | 0
2 | Titan | 40
ID matches in both tables
You should consider another database design to handle this case.
But to answer your question, you can create a view :
create view Differences2 as (
select t1.id, t1.price - t2.price
from t1, t2
where t1.id = t2.id
)
As you told both table will have same ID column you can use following query.
SELECT table1.ID, table1.Name, (table1.Price-table2.Price) AS Price
FROM table1
INNER JOIN table2 ON table1.ID = table2.ID
If you want to update record you can use following:
UPDATE table1
INNER JOIN table2 ON table1.ID = table2.ID
SET table1.Price = (table1.Price-table2.Price)
My two table setup is like below:
table1
+------+---------+--------------------------------------+
| id | tail | content |
+------+---------+--------------------------------------+
| 1 | abc | ... |
| 2 | def | ... |
| 3 | ghi | ... |
| 4 | def | ... |
| 5 | jkl | ... |
+------+-------+----------------------------------------+
table2
+------+--------+---------------------------------------+
| id | tailID | value | others |
+------+--------+---------------------------------------+
| 1 | 2 | 412 | |
| 2 | 3 | 215 | |
| 1 | 2 | 571 | |
| 1 | 4 | 123 | |
+------+--------+---------------------------------------+
I like to get all columns from this two tables in a row with matched tail = tailID but not duplicate rows which has same tail.
For the duplicate TAIL, just need to get the single row of max VALUE of same tail.
I am currently using
SELECT table1.tail, table2.other_column
FROM table1
INNER JOIN table2
on table1.id = table2.tailID
WHERE table1.some_coloum = "a sepecific string"
ORDER BY table2.value
But it returns many duplicates of same tail.
I just need to have single row for duplicate TAIL with hightes VALUE of table2.
DISTINCT with CROSS APPLY:
SELECT DISTINCT t1.tail,
t2.other_column,
t3.[value]
FROM table1 t1
CROSS APPLY (
SELECT tailid,
MAX([value]) as [value]
FROM table2
WHERE tailid = t1.id
GROUP BY tailid
) as t3
INNER JOIN table2 t2
ON t2.tailid = t3.tailid AND t3.[value] = t2.[value]
WHERE t1.some_coloum = "a sepecific string"
First group table2 then join
SELECT table1.tail, table2.other_column
FROM table1
INNER JOIN (
SELECT tailID, max(value) as value
FROM table2
GROUP BY tailID
) t2g ON t2g.tailID = table1.ID
INNER JOIN table2
on t2g.tailID = table2.tailID AND t2g.value = table2.value
WHERE table1.some_coloum = "a sepecific string"
ORDER BY table2.value
The query still may return multiple rows for a table1 row if there are 2 or more rows in table2 with the same max(value) and tailID.
Selected only rows where is MAX value of column value
SELECT table1.tail, MAX(table2.value)
FROM
table1
INNER JOIN table2 ON table1.id = table2.tailID
WHERE table1.content = "test"
http://sqlfiddle.com/#!9/b70d29/3/0
I want to show all the results from Table1 based on some select condition being true, and have a variable be set to 0 or 1 for each result from Table1 based on some satisfied condition with Table2.
SELECT * FROM Table1 WHERE Some_Condition=true
Foreach Table1.Name
SELECT IF(TID IS NULL, 0, 1) AS Variable FROM Table2
WHERE
Table2.Name=Table1.Name AND Table2.Val='p'
How can I make this all into one SQL call?
example call I would like to see is:
Table1:
+----+-------------------+
| ID | Name |
+----+-------------------+
| 1 | John |
+----+-------------------+
| 2 | Alan |
+----+-------------------+
Table2: So here Alan exists AND Val='p', not just existing
+-------+-----------+-----+
| TID | Name | Val |
+-------+-----------+-----+
| 1 | Alan | p |
+-------+-----------+-----+
SQL result I want from a SINGLE SELECT statement:
+------+----------+
| Name | Variable |
+------+----------+
| John | 0 |
+------+----------+
| Alan | 1 |
+------+----------+
A LEFT JOIN and a CASE statement may work for you. Please see query below.
SELECT A.Name AS item, (CASE WHEN B.Val='p' THEN 1 ELSE 0 END) AS Variable
FROM Table1 A LEFT JOIN Table2 B ON (A.Name=B.Name)
I think you just want a JOIN:
SELECT t2.Name, IF(Tt2.ID IS NULL, 0, 1) AS Variable
FROM Table2 t2 JOIN
Table1 t1
ON t2.Name = t1.Name
WHERE t2.Val = 'p' AND <some condition on t1> = true;
In MySQL, you can simplify the SELECT to:
SELECT t2.Name, (Tt2.ID IS NOT NULL) AS Variable
Note that I added the name to the SELECT, although it is not in your sample SQL.
You need LEFT JOIN Table2 to include all rows from Table1 even if row in Table2 not exists. And then in Variable column just check if Table2.TID is presented (i.e. not null).
SELECT Name, (Table2.TID IS NOT NULL) AS Variable
FROM Table1
LEFT JOIN Table2 ON Table2.Name=Table1.Name AND Table2.Val='p'
Or it can be done with IF():
SELECT Name, IF(Table2.TID IS NULL, 0, 1) AS Variable
FROM Table1
LEFT JOIN Table2 ON Table2.Name=Table1.Name AND Table2.Val='p'
I'm working on a tricky query and just don't understand how to approach it since neither JOIN gives me desirable result.
I have two tables:
Table1:
id
value
Tabel2:
id
table1_id
parameter (1,0)
value
I need to select everything from Table_1, but if there is a row in Table2 with table1_id = table1.id and parameter = 1, I want to include table2.value in the outcome. Note, that there can be multiple rows with table1_id = table1.id in Table2, but only one with parameter=1.
So, what I'm looking to get as a a result
table1.id | table1.value | table2.parameter |table2.value
1 | v1 | |
2 | v1 | 1 | v2
3 | v1 | |
4 | v1 | 1 | v2
Can someone help me with a query. Thank you for your time.
SELECT *
FROM
Table1 LEFT JOIN Table2
ON (Table1.id = Table2.table1_id AND Table2.parameter = 1)
;
You can use left join and case when for showing the table2 value
select
t1.id,
t1.value,
t2.parameter,
case when t2.table_id is not null and t2.parameter = 1 then t2.value else null end as table2_value
from table1 t1
left join table2 t2 on t2.table1_id = t1.id
I'm using the following query to select data from 3 different tables. tbl_invoices and tbl_clients have unique records. Each tbl_invoices record has multiple tbl_invoice_entries records:
$query = 'SELECT T1.*, T2.*, T3.*
FROM tbl_invoices T1
LEFT JOIN tbl_invoice_entries T2
ON T1.number = T2.invoice_number
LEFT JOIN tbl_clients T3
ON T1.client = T3.client_id
WHERE date_format(date, '%Y') = ".$_POST['year']." AND date_format(date, '%c') = ".$_POST['month']." ORDER BY date, number ASC'
$stmt = $conn->prepare($query)
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
This currently returns all records in tbl_invoice_entries. How do I change my query in order to only return the first tbl_invoice_entries record for each tbl_invoices record.
Here are the tables:
tbl_clients
+----+-----------+----------+
| id | firstname | lastname |
+----+-----------+----------+
| 1 | John | Doe |
| 2 | Jane | Doe |
+----+-----------+----------+
tbl_invoices
+----+--------+--------+------------+
| id | number | client | date |
+----+--------+--------+------------+
| 1 | 14 | 1 | 2015-07-14 |
| 1 | 15 | 2 | 2015-07-14 |
+----+--------+--------+------------+
tbl_invoice_entries
+----+----------------+------------+
| id | invoice_number | produkt |
+----+----------------+------------+
| 1 | 14 | Fish |
| 2 | 14 | Bread |
| 3 | 15 | Vegetables |
| 4 | 15 | Fruit |
+----+----------------+------------+
So the results I'm looking for are:
John Doe 14 Fish 2015-07-14
Jane Doe 15 Vegetables 2015-07-14
Thanks for any help!
By linking the invoice_entries table not directly through the invoice number but by the id of its first entry you can achieve what you want:
SELECT firstname,lastname,number,product,date
FROM tbl_invoices T1
LEFT JOIN tbl_invoice_entries T2
ON T2.id =(select min(id) from tbl_invoice_entries
where invoice_number=number)
LEFT JOIN tbl_clients T3
ON T1.client = T3.id
WHERE ...
You need to tell the RDBMS what you intend by the first row. There is no natural order in tuples. If you want the tuple with lowest ID given the same invoice_number, then it would require another query
SELECT tbl1.* FROM tbl_invoice_entries AS tbl1
JOIN ( SELECT MIN(id) AS id, invoice_number FROM tbl_invoice_entries
GROUP BY invoice_number ) AS tbl2
USING (id);
The above query is equivalent to tbl_invoice_entries but only has the lowest ID of each invoice number. You can do it as a VIEW (actually two, since you can't use subqueries in a VIEW):
CREATE VIEW tbl_invoice_entries_firstnumber AS
SELECT MIN(id) AS id, invoice_number
FROM tbl_invoice_entries
GROUP BY invoice_number;
CREATE VIEW tbl_invoice_entries_first AS
SELECT tbl1.* FROM tbl_invoice_entries AS tbl1
JOIN tbl_invoice_entries_firstnumber
USING (id);
After that you can use tbl_invoice_entries_first instead of tbl_invoice_entries in your current query.
Keep in mind that the view is dynamic, so it is only a shorthand for a more complex query. This means that your current query will become more complicated and require a longer time:
SELECT T1.*, T2.*, T3.*
FROM tbl_invoices AS T1
LEFT JOIN tbl_invoice_entries_first AS T2
ON T1.number = T2.invoice_number
LEFT JOIN tbl_clients AS T3
ON T1.client = T3.id; -- you have no client_id in T3
I have set up a fiddle here.
Or you can modify your query more, and add a JOIN condition on T2 so that it only fetches, again, the minimum ID - or whatever ordering condition you prefer:
SELECT T1.*, T2.*, T3.*
FROM tbl_invoices AS T1
LEFT JOIN tbl_invoice_entries AS T2
ON (
-- (( T1.number = T2.invoice_number AND )) --
T2.id = (
SELECT MIN(id) FROM tbl_invoice_entries
WHERE invoice_number = number
))
LEFT JOIN tbl_clients AS T3
ON T1.client = T3.id;
UPDATE: The check on number was commented out (see also #cars10's solution) because it is carried over by the inner subquery.
Finally you can do this in code, i.e. you save the value of the previous tuple and order the query as needed; then discard all unneeded tuples. If you have few entries per invoice, this might be worthwhile:
// pseudo code
if (prev.client == tuple.client)
and
(prev.invoice == tuple.invoice)
continue;
prev = tuple;
-- use tuple.