SQL select data from multiple tables - mysql

I'm trying to select from multiples tables(10+) that are in the following format using mySQL.
+----------table(n)-----------+
+-----------------------------+
| url | id | ... |
+-----------+-----------+-----+
| url1.com | 12345678 | ... |
| url2.com | 45832458 | ... |
What I need to do is retrieve the id from each table for a given URL and return it in a single row like so.
+--------------table(n)--------------+
+------------------------------------+
| url | table(n) | table(n+1) |
+-----------+-----------+------------+
| url1.com | 12345678 | 8182735 |
But the URL might not exist for a given table, so I just need to retrieve all the ids from the tables where the URL is found.
For example, I have 10 tables and a URL/id is in 4 of them. I need to retrieve these 4, in a single row. I've tried to use aliases for columns along with various JOIN combinations to no avail.
Any help would be appreciated.

You can do this with a union all and group by:
select url,
max(id1) as id1, max(id2) as id2, . . .
from ((select url, id as id1, NULL as id2, . . . from table1) union all
(select url, NULL as id1, id as id2, . . . from table1) union all
. . .
) t
group by url;

try like this
SELECT tu.URL,COALESCE(table_1.id,0) AS table_1,COALESCE(table_2.id,0) As
table_2,......,COALESCE(table_n.id,0) AS table_n FROM Table_URL tu
LEFT JOIN table_1 ON tu.URL = table_1.URL
LEFT JOIN table_2 ON tu.URL = table_2.URL
.
.
LEFT JOIN table_n ON tu.URL = table_n.URL

You want a variable number of columns generated by your SQL statement, and you cannot do that with MySQL.
You can see some techniques to get around it here: MySQL pivot row into dynamic number of columns
Many reporting tools will let you do things like you want to, but using some sort of prepared statement hack with MySQL would be the only way to do it:
http://buysql.com/mysql/14-how-to-automate-pivot-tables.html

Related

Remove SQL duplicates

I'm totally new in SQL. I never used it and just need a simple answer because I don't have time to learn SQL right now :(. I need to remove duplicated records from my local DB. Case looks like this:
| id | type | ... |
-------------------
| 1 | test | ... |
| 1 | test2 | ... |
| 1 | test | ... |
| 1 | test | ... |
I want to remove all duplicated record which has the same id and type but leave only on record. Like this:
| id | type | ... |
-------------------
| 1 | test | ... |
| 1 | test2 | ... |
Using delete by Id is impossible. I have 50k records and I want to remove all duplicated records. When ID and Type are the same.
Please try this
First Way
SELECT id, type
FROM table_name
Group by id, type
Second Way
SELECT DISTINCT id, type
FROM table_name;
A TSQL sample code that might help:
WITH tbl_alias AS
(
SELECT id, type,
RN = ROW_NUMBER()OVER(PARTITION BY id, type ORDER BY id)
FROM tbl
)
DELETE FROM tbl_alias WHERE RN > 1
Also you can try How to delete duplicates on a MySQL table?
.
SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
SELECT DISTINCT column1, column2, ...
FROM table_name;
In your table
SELECT DISTINCT id, type, ...
FROM table_name;
you just need to use the keyword distinct when selecting mate.. try like this
SELECT DISTINCT id, type, blah blah blah FROM your_table; // this should take care of em
You should replace your table grouping by id and type, and using an aggregate function on the other fields.
You should add to your question the definition of your table and specify the rule to use to get the other fields. Anyway, this is a simple solution:
-- Create a temp copy of original table with distinct values
CREATE TEMPORARY TABLE copy_table1
SELECT id, type, MIN(field3) AS field3, ...
FROM table1
GROUP BY id, type;
-- Empty original table
DELETE FROM table1;
-- Insert distinct data into original table
INSERT INTO table1 (id, type, field3, ...)
SELECT id, type, field3, ...
FROM copy_table1;

How change colums for rows in a query

I have a survey with many objectives for assess from 1 to 5 in my web page. I send the survey to my database in my table of survey.
For example
obj1value | obj2value | obj3value ... | obj17value |
I have a value for every survey.
Now I need to do some charts for present a report of the survey.
I need to add up the totals for each objective.
I have this query
SELECT SUM(obj1_value) AS objective1, SUM(obj2_value) AS objective2, SUM(obj3_value) AS objective3, FROM tbl_survey
I have this till objective17 and the query returns
| objective1 | objective2 | objective3 |
| --- | --- | --- |
| 17 | 12 | 5 |
But I need to change the query like this
_objective_ | _Value_
objective1 | 17
objective2 | 12
objective3 | 5
Objective17 | n
Someone can help me with the query to optimize because in this way I can convert the table php in json and took a bar chart library so easy.
Thank you
It is probably easiest to do the transformation in PHP. One method in MySQL is a simple UNION ALL:
SELECT 'obj1_value', SUM(obj1_value)
FROM tbl_survey
UNION ALL
SELECT 'obj2_value', SUM(obj2_value)
FROM tbl_survey
UNION ALL
. . .
The downside to this approach is that the table is scanned 17 times, so it will probably take about 17 times as long.
You can improve performance by doing an unpivot. Here is one method in MySQL:
SELECT o.obj,
(CASE WHEN obj = 'objective1' THEN objective1
WHEN obj = 'objective2' THEN objective2
. . .
END) as value
FROM (SELECT SUM(obj1_value) AS objective1, SUM(obj2_value) AS objective2,
SUM(obj3_value) AS objective3, . . .
FROM tbl_survey
) s CROSS JOIN
(SELECT 'objective1' as obj UNION ALL
SELECT 'objective2' as obj UNION ALL
. . .
) o;
the solution for this problem is PIVOT AN UNPOVIT , and you can change the out put us you want , this is tutorial can help you

MySQL returning arrays from subqueries, and NULL

I have two tables, "records", and "info".
The "records" table looks like:
mysql> SELECT * FROM records WHERE num = '7';
+-----+--------+----+------+-----+-----+------------+-----------+----------+---------------------+
| id | city | st | type | num | val | startdate | status | comments | updated |
+-----+--------+----+------+-----+-----+------------+-----------+----------+---------------------+
| 124 | Encino | CA | AAA | 7 | 1 | 1993-09-01 | allocated | | 2014-02-26 08:16:07 |
+-----+--------+----+------+-----+-----+------------+-----------+----------+---------------------+
and so on. Think of the "num" field in this table as a Company ID.
The "info" table contains information about certain companies, and uses that company id as a unique identifier. Not all companies listed in "records" will be in "info". An example of the "info" table:
mysql> SELECT * FROM info LIMIT 2;
+-----+-------+--------------------------+---------------------+
| org | name | description | updated |
+-----+-------+--------------------------+---------------------+
| 0 | ACME | | 2014-02-19 10:35:39 |
| 1 | AT&T | Some Phone Company, Inc. | 2014-02-18 15:29:50 |
+-----+-------+--------------------------+---------------------+
So "org" here will match "num" in the first table.
I want to be able to run a query that returns, on one line, everything but 'id', 'type' and 'val' from the 1st table, and IF APPLICABLE, the 'name' and 'description' from the 2nd table.
I can achieve what I want using this query:
SELECT city,st,num,startdate,status,comments,updated, \
( SELECT name FROM info WHERE org = '7') AS name, \
( SELECT description FROM info WHERE org = '7') AS description \
FROM records WHERE num = '7'
But I see at least two problems with it:
It seems inefficient to run two subqueries
When there is no record in "info", NULL is printed for the name and
description. I would like to print some string instead.
To address the first problem, I tried to return an array. But when no corresponding record exists in the "info" table, then I get nothing, not even the valid info from the "records" table. Here's my array query:
SELECT city,st,num,startdate,status,comments,updated,asinfo.name AS name,asinfo.description AS description \
FROM records, \
( SELECT name,description FROM info WHERE org = '7') AS asinfo \
WHERE num = '7'
This query works fine if a given company id exists in both tables.
To address the second problem, I tried various incantations of IFNULL and coalesce, to no avail.
I'd appreciate any insight.
Thanks.
Apply LEFT JOIN syntax:
SELECT
r.city,
r.st,
r.num,
r.startdate,
r.status,
r.comments,
r.updated,
IF(d.name IS NULL, 'Default', d.name) AS name,
IF(d.description IS NULL, 'Default', d.description) AS description
FROM
records AS r
LEFT JOIN info AS d ON r.num=d.org
WHERE
r.num='7'
that will work such way: LEFT JOIN looks into first table, and, if there are no corresponding records in second, it applies NULL. So you'll discover that with IF (or IFNULL) and do substitution of default string.
Use a LEFT JOIN to get null values when there's no matching row in the info table.
SELECT city,st,num,startdate,status,comments,updated,
IFNULL(name, 'Default Name') name,
IFNULL(description, 'Default Description') description
FROM records r
LEFT JOIN info i ON r.num = i.org
WHERE r.num = 7
It sounds like a simple LEFT JOIN from record to info will do the trick.
LEFT JOIN rather than JOIN in order to ensure you ALWAYS get all rows from the record table, and then the corresponding data in info table if a xref exists for that ID.
Whether using your sub-queries or using joins, if you always want to see all rows in record table, then you will always get NULLs corresponding to the info table where no xref exists. The only way to avoid that is to run some code that calls everything from record, and then iterates over the results to query info, to conditionally add to the record data.

MYSQL Echo Value only once from multible columns

I would like print out a list of names, each name only once.
The Problem: I have two different columns with names in them, yet I want to display each name only once, not depending on the column.
I am going to echo the result with PHP, so also loop's or other PHP actions are possible if there is no MYSQL only solution.
To visualise an example: (I also have an ID column as shown below)
ID |Name1 | Name2
-------|-------|-------
01 | A | B
02 | A | C
03 | B | A
As seen above there are the same names in both columns, yet I want to get each name only once.
Locking like this (for example):
(List:)
A
B
C
something like this should do it:
select distinct name
from (
select Name1 name from table_name
union all
select Name2 name from table_name
)
try this:
select distinct(name) from (select a.name1 as name from tablename as a
union select b.name2 as name from tablename as b)name;

Mysql-Select all tables from a database

I've a database called test and i've tables called x,y,z.
How do i select x,y,z and there is a column called date IN X,Y,Z check whether there is a particular date.
Is there any build in function that does this?
update
SELECT column date from all tables which is in a database called test
Thanks in advance!!
As far as I know, in SQL you cannot 'select a table', you can select some
column(s) from one or many tables at once. The result of such a query is an another table (temporary table) that you retrieve the data from.
Please be more specific about what exactly you want to do (e.g.: "I want to select a column 'z' from table 'tableA' and column 'y' from table 'tableB'") - then I'm sure your question has a pretty simple answer :)
SELECT x.date AS x_date, y.date AS y_date, z.date AS z_date FROM x,y,z;
That produces a result:
+---------+---------+---------+
| x_date | y_date | z_date |
+---------+---------+---------+
| | | |
| | | |
+---------+---------+---------+
Alternatively you can get everything in one column by ussuing a query:
SELECT date FROM x
UNION ALL
SELECT date FROM y
UNION ALL
SELECT date FROM z;
That produces a result:
+-------+
| date |
+-------+
| |
| |
+-------+
In the example above you would get also duplicate values in the single column. If you want to avoid duplicates replace 'UNION ALL' with 'UNION'
I'm still not sure if I undestood what you really want ot achieve, but I still hope that helps
Also take a look at:
http://www.w3schools.com/sql/sql_union.asp
http://www.sql-tutorial.net/SQL-JOIN.asp