I have a row with some values hyphen-delimited:
table: live_customers
row: areas
id | areas
1 | 10-20-30
2 | 40-50-60
...
Using this...
LEFT JOIN $table5 AS table5 ON live.areas REGEXP CONCAT('(^|-) ?',table5.id,' ?($|-)')
My results looks like:
(tab id:1) area: 10
(tab id:1) area: 20
...
(tab id:2) area: 40
...
But i expect:
(tab id:1) area: 10,20,30
(tab id:2) area: 40,50,60
How could i solve that?
EDIT:
The full query looks like:
SELECT live.*,
live.id AS lid,
table1.id, table1.value AS tn_val,
table2.id, table2.value AS tp_val,
table3.id, table3.value AS ht_val,
table5.id, table5.value AS ar_val
FROM $dblist AS live
LEFT JOIN $table1 AS table1 ON live.town = table1.id
LEFT JOIN $table2 AS table2 ON live.htype = table2.id
LEFT JOIN $table3 AS table3 ON live.ht = table3.id
LEFT JOIN $table5 AS table5 ON live.areas REGEXP CONCAT('(^|-) ?',table5.id,' ?($|-)')
ORDER BY live.id ASC
PHP echoes:
...
if ($post['areas']){ // Debugging areas stuff
echo '<strong>'.$_areas.': (ar_val)</strong> '.$post['ar_val'].'<p>';
echo '<strong>'.$_areas.': (areas)</strong> '.$post['areas'].'<p>';
}
...
EDIT2:
It's quite hard for me to explain my issue in English, but i'm trying the best i can :)
in the table "live_customers" i does have this:
id | areas
1 | 10-20-30
2 | 40-50-60
...
in the table "areas" (that is a completely different table):
id | value
38 | Zone1
39 | Zone2
40 | Zone3
...
In the SQL query you see just tables variables because i previousvly declared them at the top of page:
$table5 = 'areas';
$dblist = 'live_customers';
etc..
Solution
Thanks anyone for their answers and for let me know "GROUP_CONCAT".
Here is my solution:
SELECT live.*,
live.id AS lid,
table1.id, table1.value AS tn_val,
table2.id, table2.value AS tp_val,
table3.id, table3.value AS ht_val,
table5.id, GROUP_CONCAT(table5.value) AS ar_val
FROM $dblist AS live
LEFT JOIN $table1 AS table1 ON live.town = table1.id
LEFT JOIN $table2 AS table2 ON live.htype = table2.id
LEFT JOIN $table3 AS table3 ON live.ht = table3.id
LEFT JOIN $table5 AS table5 ON FIND_IN_SET(table5.id, REPLACE(live.areas, '-', ','))
GROUP BY live.id
Result is what i expected ^^
Take it together with GROUP_CONCAT()
First thing to say is that your schema violates First Normal Form (1NF) in that the column areas is not atomic. You should not be putting 3 different values in one column.
Next you say you have a table called live_customers with a row called areas. This is nonsense. Rows do not have names, columns do. You show a bit of table with 2 columns id and areas. What table is this?
Next in the query there is no mention of a table called live_customers.
Next, if there is a column called areas in the table with the alias of live, then the output should contain that column since you are selecting live.*. That being the case, your results cannot be what you showed us, since it would contain a results column with data like 10-20-30
Finally those cannot be the results of the posted query since I can see a results column of lid specified.
If you would care to take some time over ensuring that the questionyou post makes sense, then you might get a reasonable answer.
Related
I have a problem to split data from attendance machine. The data source after export from it like this:
id name att
1 John 01/04/2015 7:59:00
1 John 01/04/2015 17:44:00
1 John 02/04/2015 7:50:00
1 John 02/04/2015 18:14
Where record (in and out) from fingerprint time save in one column. And I want to split the data to be like this:
id name in out
1 John 01/04/2015 7:59:00 01/04/2015 17:44:00
1 John 02/04/2015 7:50:00 02/04/2015 18:14:00
How to split those record into 2 column in MySQL or PHP (maybe)? Thank you.
Assuming there is only one in/out per day, it's as simple as self-joining on the date and greater time.
select t1.id, t1.name, t1.att as `in`, t2.att as `out`
from table1 t1
inner join table1 t2
on date(t1.att) = date(t2.att) and t1.id = t2.id
and t2.att > t1.att
sql fiddle demo
If you want to create a brand new table with this data, so you can get rid of the import, you just need to use this query as the input to create table, like so:
create table new_table
as
select t1.id, t1.name, t1.att as `in`, t2.att as `out`
from table1 t1
inner join table1 t2
on date(t1.att) = date(t2.att) and t1.id = t2.id
and t2.att > t1.att
You could try this one.
SELECT a.userID,a.name,min(a.att)as `in`,max(a.att) as `out`
FROM
(
SELECT userID,name,str_to_date(att,'%m/%d/%Y%T') as att,str_to_date(att,'%m/%d/%Y') as attd
FROM attendance
) as a
GROUP BY a.userID,a.attd
I have an instrument list and teachers instrument list.
I would like to get a full instrument list with id and name.
Then check the teachers_instrument table for their instruments and if a specific teacher has the instrument add NULL or 1 value in a new column.
I can then take this to loop over some instrument checkboxes in Codeigniter, it just seems to make more sense to pull the data as I need it from the DB but am struggling to write the query.
teaching_instrument_list
- id
- instrument_name
teachers_instruments
- id
- teacher_id
- teacher_instrument_id
SELECT
a.instrument,
a.id
FROM
teaching_instrument_list a
LEFT JOIN
(
SELECT teachers_instruments.teacher_instrument_id
FROM teachers_instruments
WHERE teacher_id = 170
) b ON a.id = b.teacher_instrument_id
my query would look like this:
instrument name id value
--------------- -- -----
woodwinds 1 if the teacher has this instrument, set 1
brass 2 0
strings 3 1
One possible approach:
SELECT i.instrument_name, COUNT(ti.teacher_id) AS used_by
FROM teaching_instrument_list AS i
LEFT JOIN teachers_instruments AS ti
ON ti.teacher_instrument_id = i.id
GROUP BY ti.teacher_instrument_id
ORDER BY i.id;
Here's SQL Fiddle (tables' naming is a bit different).
Explanation: with LEFT JOIN on instrument_id we'll get as many teacher_id values for each instrument as teachers using it are - or just a single NULL value, if none uses it. The next step is to use GROUP BY and COUNT() to, well, group the result set by instruments and count their users (excluding NULL-valued rows).
If what you want is to show all the instruments and some flag showing whether or now a teacher uses it, you need another LEFT JOIN:
SELECT i.instrument_name, NOT ISNULL(teacher_id) AS in_use
FROM teaching_instrument_list AS i
LEFT JOIN teachers_instruments AS ti
ON ti.teacher_instrument_id = i.id
AND ti.teacher_id = :teacher_id;
Demo.
Well this can be achieved like this
SELECT
id,
instrument_name,
if(ti.teacher_instrument_id IS NULL,0,1) as `Value`
from teaching_instrument_list as til
LEFT JOIN teachers_instruments as ti
on ti.teacher_instrument_id = til.id
Add a column and check for teacher_instrument_id. If found set Value to 1 else 0.
I'm very new with SQL and need assistance on how I can accomplish this task using the correct query.
I have 2 tables that I need to use. Table "TB1" has:
id Name
1 bob
2 blow
3 joe
table "TB2" has:
compid property
1 bob
2 blow
I am trying to get which compid is missing in "TB2" and insert it from "TB1"
the query I am doing is:
SELECT id, name from TB1, TB2 where id <> compid
what I get is 2 ouputs of Id 1, and 2, and 3 outputs from id 3. by using php:
for($i=0;$i <= mysql_num_rows($comp)-1; $i++)
{
echo mysql_result($comp, $i, 0)."<br>";
}
and I expected the ouput 3 but instead got this:
1
1
2
2
3
3
3
I understand its comparing all the rows within the table but is there a way to achieve what I am looking for?
Thanks for your time.
You are performing an implicit Cartesian JOIN which results in every row against every other row. You need to specify what attribute JOINs the two tables.
Using implicit syntax (not recommended):
SELECT id, name
FROM TB1, TB2
WHERE id <> compid
AND TB1.Name = TB2.property <-- Column join
Using explicit syntax:
SELECT id, name
FROM TB1
JOIN TB2
ON TB2.property = TB1.Name <-- Column join
WHERE id <> compid
To accomplish your goal you would need something along the lines of:
SELECT TB1.id, TB1.name
FROM TB1
LEFT JOIN TB2
ON TB2.property = TB1.Name
WHERE TB2.compid IS NULL
See it in action
It's best practice to always alias the columns you select to prevent ambiguity.
To select it you can do:
SELECT *
FROM TB1
WHERE id NOT IN (
SELECT compid
FROM TB2
);
I have a hard nut to crack with joing 3 tables.
I have a newsletter_items, newsletter_fields and newsletter_mailgroups which I want to be joined to get a list of newsletters.
The newsletter_items contains the fields:
letter_id, letter_date, receivers, template, status
That can look like
1, 1234567899, 1,2 (comma separated), standard.html, 1
newsletter_fields contains the fields:
field_uid, field_name, field_content, field_letter_uid
That can look like
1, letter_headline, A great headline, 1
where field_letter_uid is the newsletter for which the field belongs to.
and newsletter_mailgroups contains the fields:
mailgroup_id, mailgroup_name, number_of_members
That can look like
1, Group1, 233
2, Group2, 124
3, Group3, 54
What I want is to combine these 3 tables to that I can get a list of all the newsletter like this:
Letter date | Letter headline | Receivers | Status
2008-01-01 12:00:00 | A great headline | Group1, Group 2 | 1
So in short I want my SQL query to join the 3 tables and in that process select the receivers from the mailgroup table and display them comma separated like Group1, Group 2
This what I got now
SELECT A.*, B.* FROM newsletter_items A, newsletter_fields B, WHERE B.field_letter_uid = A.letter_id AND field_name = 'letter_headline' AND A.template = '". $template ."';
But I can't seem to figure out how to get the mailgroups into that.
I recommend that you make your joins explicit.
It makes it easier to debug your query and to change inner with left joins.
There is absolutely never a good reason to use SQL '89 implicit join syntax.
SELECT ni.*
, nf.*
, group_concat(nm.mailgroup_name) as mailgroups
FROM newsletter_items ni
INNER JOIN newsletter_fields nf
ON (nf.field_letter_uid = ni.letter_id)
INNER JOIN newsletter_mailgroups nm
ON (find_in_set(nm.mailgroup_id, ni.receivers))
WHERE
nf.field_name = 'letter_headline'
ni.template = '". $template ."'
GROUP BY ni.letter_id;
Regarding your database design.
I recommend you normalize your database, that means that you move the comma separated fields into a different table.
So you make a table receivers
Receivers
----------
id integer auto_increment primary key
letter_id integer not null foreign key references newsletter_items(letter_id)
value integer not null
You then remove the field receiver from the table newsletter_items
Your query then changes into:
SELECT ni.*
, group_concat(r.value) as receivers
, nf.*
, group_concat(nm.mailgroup_name) as mailgroups
FROM newsletter_items ni
INNER JOIN newsletter_fields nf
ON (nf.field_letter_uid = ni.letter_id)
INNER JOIN newsletter_mailgroups nm
ON (find_in_set(nm.mailgroup_id, ni.receivers))
LEFT JOIN receiver r ON (r.letter_id = ni.letter_id)
WHERE
nf.field_name = 'letter_headline'
ni.template = '". $template ."'
GROUP BY ni.letter_id;
This change should also speed up your query significantly.
If it's allowed, why don't you create a new table called newsletter_item_receivers where you could store letter_id, receiver_id fields?
Having comma separated values in a field like this usually means you're missing a table :)
Edit:
By using CSV, you are making your life miserable when you want to retrieve an answer to "give me all newsletters that receiver_id=5 receives" :)
Here's a good answer to a similar question on SO: Comma separated values in a database field
Edit2:
If I understand your table relationships correctly then it would be something like this:
SELECT
a.letter_date,
b.receiver_id,
a.status
FROM newsletter_items_receivers b
LEFT OUTER JOIN newsletter_items a ON (a.letter_id = b.letter_id)
LEFT OUTER JOIN newsletter_mailgroups m ON (m.mailgroup_id = b.receiver_id)
NOTE! This query WILL NOT return a newsletter when there are no receivers of that newsletter.
If you need that functionality you can try something like this:
SELECT
x.letter_date,
y.mailgroup_name,
x.status
FROM (
SELECT
a.letter_date,
b.receiver_id,
a.status
FROM newsletter_items a
LEFT OUTER JOIN newsletter_items_rec b ON (b.letter_id = a.letter_id)) x
LEFT OUTER JOIN newsletter_mailgroups y ON (y.mailgroup_id = x.receiver_id)
I don't have access to SQL right now so I might have made some syntax errors (hopefully not logical ones :)).
As for why we are doing it like this, as #Konerak pointed out, you'd be well advised to read up on database normalization and why it's important.
You can start with this article from about.com, just glanced over it seems an OK read
http://databases.about.com/od/specificproducts/a/normalization.htm
Also, it would be good if you'd keep fields names the same across multiple tables.
For example you have letter_id in newsletter_items, but you have field_letter_uid in newsletter_fields. Just a thought :)
Try to use
SELECT A.*, B.*, group_concat(C.mailgroup_name SEPARATOR ',')
FROM newsletter_items A, newsletter_fields B, newsletter_mailgroups C
WHERE B.field_letter_uid = A.letter_id
AND field_name = 'letter_headline'
AND A.template = '". $template ."'
and find_in_set(c.mailgroup_id, A.receivers)
group by A.letter_id;
I'm trying to join two tables. The first table has a list of 11 items which are 'site_names' with an auto id field of 'id'. The second table that I want to connect has an auto id field of 'desc_id' and another field of 'descriptions'. This second table currently has 3 rows of data that I want displayed only for id 1 in table 1.
So, I want to accomplish is to connect the first site in table one with an id of '1' to the entire second table.
I can't seem to figure out how connect only the first entry(id=1) in table 1 to all the rows in table 2 (tb.1->id->1 to tbl.2->desc_id->1,2,3).
I hope that made sense. Any help would be great. Thanks
Try:
select site_name, descriptions
from table_1
inner join table_2
on 1 = 1
where table_1.site_id = 1
This should join give you what you want.
OK - based on the comment, I'm guessing what you want is:
site1 | desc1 | desc2 | desc3
all on one row. This is a bit trickier - particularly if you want it to remain open to an arbitrary number of descriptions. For just 3 (or, really, any limited subset, but as the number goes up, it gets ugly), you could do:
select site_name, t2.desc, t3.desc, t4.desc
from table_1
inner join table_2 t2
on t2.desc_id = 1
inner join table_2 t3
on t3.desc_id = 2
inner join table_2 t4
on t4.desc_id = 3
where site_id = 1
This kind of stuff is highly irregular though. It seems to me like something about your schema is probably not quite right to generate this sort of requirement.
Here is the query:
<?php
$mysql = new mysqli('localhost', 'root', 'root') or die('counld not connect');
$result = $mysql->query("SELECT ajax_demo.explore.site_name, anthony1.property.descriptions FROM ajax_demo.explore INNER JOIN anthony1.property ON ajax_demo.explore.id = anthony1.property.desc_id") or die($mysql->error);
if($result)
{
while($row = $result->fetch_object())
{
$id = $row->id;
$siteName = $row->site_name;
$siteDescription = $row->site_description;
echo "$siteName";
echo "$siteDescription";
}
}
?>
I may be missing something here, but it sounds to me like you need to add a foreign key to the Site table. If I understand your question correctly, your tables should look something like this:
Site
- SiteID
- DescriptionID
- SiteName
Description
- DescriptionID
- Description
Then your query to get Sites and their associated Descriptions would look like this:
SELECT
s.SiteName,
d.Description
FROM
Site s INNER JOIN Description d
ON s.DescriptionID = d.DescriptionID
This table structure assumes that multiple Sites share single Descriptions (as per your posted question).