How do I mysql select with aliases from another table? - mysql

I'm working with a CMS system where I cannot control database column names. And I've got two related tables:
Table: content
+------------+----------+----------+----------+----------+
| content_id | column_1 | column_2 | column_3 | column_4 |
+------------+----------+----------+----------+----------+
| 1 | stuff | junk | text | info |
| 2 | trash | blah | what | bio |
+------------+----------+----------+----------+----------+
Table: column_names
+------------+-------------+
| column_id | column_name |
+------------+-------------+
| 1 | good_text |
| 2 | bad_text |
| 3 | blue_text |
| 4 | red_text |
+------------+-------------+
What I'd like to do here is select from the first table, but select the columns AS the column_name from the second table. So my result would look like:
+------------+-----------+----------+-----------+----------+
| content_id | good_text | bad_text | blue_text | red_text |
+------------+-----------+----------+-----------+----------+
| 1 | stuff | junk | text | info |
| 2 | trash | blah | what | bio |
+------------+-----------+----------+-----------+----------+

There is no way to do this, but as long as your columns won't change too often, a VIEW on that table with hard-coded aliases could be sufficient.

To my knowledge you can't use subselects as the target of an AS in SQL. If I were you, I'd load the data from column_names into an array (I'd also cache it in an in-memory DB since it isn't going to change all that often), then use that array to build my SQL.
A very rough example (in PHP):
$column_relations = array();
$sql = "SELECT * FROM column_names;";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res))
{
$column_relations[$row['column_name']] = 'column_' . $row['column_id'];
}
$sql = sprintf("SELECT content_id, '%s' AS good_text, '%s' AS bad_text, '%s' AS blue_text, '%s' AS red_text FROM content;", $column_relations['good_text'], $column_relations['bad_text'], $column_relations['blue_text'], $column_relations['red_text']);

SELECT
cn. column_id id,
MAX(IF(content_id=1,column_1,null)) as good_text,
MAX(IF(content_id=2,column_2,null)) as bad_text,
MAX(IF(content_id=3,column_3,null)) as blue_text,
MAX(IF(content_id=4,column_4,null)) as red_text
FROM content ct
INNER JOIN column_names cn ON (cn. column_id = ct.content_id)
GROUP BY cn. column_id
Sorry, it should be LEFT JOIN, not INNER.
You cannot have a dynamic number of columns, so this solution works only if you know in advance how many
groups you might have.

Related

how to convert table columns into a table in mysql?

I know it's a bad title, but I don't know how to describe my question in a line.
I want to store following information in my database.
+----+----------+-----------+-----------+
| id | name | cluster_1 | cluster_2 |
+----+----------+-----------+-----------+
| 1 | content_1| true| false |
| 2 | content_2| false| true |
| 3 | content_3| true| true |
+----+----------+-----------+-----------+
cluster_1=true means that the content exists on the cluster_1.
As some clusters may added or deleted, I want to store my cluster information in a new table "clusters", and indicate the relation between contents and clusters with a "content_cluster" table.
table contents
+----+----------+
| id | name |
+----+----------+
| 1 | content_1|
| 2 | content_2|
| 3 | content_3|
+----+----------+
table clusters
+----+----------+
| id | name |
+----+----------+
| 1 | cluster_1|
| 2 | cluster_2|
+----+----------+
table content_cluster
+----------+----------+
|content_id|cluster_id|
+----------+----------+
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
| 3 | 2 |
+----------+----------+
But, writing in this way, I don't know how to get a content which is on cluster_1 but isn't on cluster_2, or vice versa. I have to do this query frequently. So what is the efficient way to do this?
how to get a content which is on cluster_1 but isn't on cluster_2
in general
SELECT contents.name
FROM contents
JOIN content_cluster ON contents.id = content_cluster.content_id
LEFT JOIN clusters ON clusters.id = content_cluster.cluster_id
GROUP BY contents.name
HAVING SUM(clusters.name = 'cluster_1') -- not zero, may add ">0"
AND !SUM(clusters.name = 'cluster_2') -- zero, may replace NOT ("!") with "=0"
The following should work:
-- For cluster 1
INSERT INTO new_table (content_id, cluster_id)
SELECT old_table.content_id, 1
FROM old_table
WHERE old_table.cluster_1 = TRUE;
-- For cluster 2
INSERT INTO new_table (content_id, cluster_id)
SELECT old_table.content_id, 2
FROM old_table
WHERE old_table.cluster_2 = TRUE;

MS Access Update on specific SQL select same table

I'm currently trying to update an existing database (removing duplicates).
You can see the structure as follows :
I have a database on which specific entries are marked as "Main". These entries need to be updated with data from duplicate records, only having the same name.
(Updated table to reflect my question better)
It would look like this:
+----+------+-----------------+--------------+---------+
| ID | Name | Field-To-Update | Duplication | Source |
+----+------+-----------------+--------------+---------+
| . | A | xxx | Main | 1 |
| . | A | yyy | "" | 2 |
| . | A | zzz | "" | 3 |
| . | B | foo | "" | 1 |
| . | B | bar | Main | 2 |
+----+------+-----------------+--------------+---------+
Should result in
+----+------+-----------------+--------------+-----------------------------------------------+
| ID | Name | Field-To-Update | Duplication | Source |
+----+------+-----------------+--------------+-----------------------------------------------+
| . | A | yyy | Main | 1 |
| . | A | yyy | "" | 2 |
| . | A | zzz | "" | 3 (should be updated from a specific source) |
| . | B | bar | "" | 1 |
| . | B | bar | Main | 2 (should be updated from a specific source) |
+----+------+-----------------+--------------+-----------------------------------------------+
Do any of you have an idea how to tackle this? I've tried with multiple queries for a couple of days now without any success.
you could use a update with join
update t
set t.field_to_update = x.field_to_update
from your_table t
inner join ( select name, field_to_update
from your_table
where Duplication <> 'Main') x
) on t.name = x.name
where t.Duplication = 'Main'
Bizarre requirement. You say you are updating to remove duplicates, however, it looks to me like you are creating duplicates.
There are only 2 records for each Name? Try:
UPDATE Table INNER JOIN
(SELECT Name, [Field-To-Update]
FROM Table
WHERE Duplication Is Null) AS Query1 ON
Table.Name = Query1.Name SET Table.[Field-To-Update] = [Query1]![Field-To-Update] WHERE Duplication = "Main";
Name is a reserved word in Access. Should not use reserved words as name for anything.
Darn! Did not see #scaisEdge answer before posting.
I tried the <> "Main" criteria and it did not work which was surprising - no records returned. So I switched to the Is Null parameter.
If you want to pull value from the maximum Source for each Name, then need a query that does that. Review http://allenbrowne.com/subquery-01.html#TopN. Then use that query in the above example as Query1.

Select value from table sorted by a certain order from another table

I want to select value from table sorted by a certain order.
I have a table called test that looks like this:
| date | code | value |
+----------+-----------+----------+
| 20050104 | 000005.SZ | -6359.19 |
| 20050104 | 600601.SH | -7876.34 |
| 20050104 | 600602.SH | -25693.3 |
| 20050104 | 600651.SH | NULL |
| 20050104 | 600652.SH | -15309.9 |
...
| 20050105 | 000005.SZ | -4276.28 |
| 20050105 | 600601.SH | -3214.56 |
...
| 20170405 | 000005.SZ | 23978.13 |
| 20170405 | 600601.SH | 32212.54 |
Right now I want to select only one date, say date = 20050104, and then sort the data by a certain order (the order that each stock was listed in the stock market).
I have another table called stock_code which stores the correct order:
+---------+-----------+
| code_id | code |
+---------+-----------+
| 1 | 000002.SZ |
| 2 | 000004.SZ |
| 3 | 600656.SH |
| 4 | 600651.SH |
| 5 | 600652.SH |
| 6 | 600653.SH |
| 7 | 600654.SH |
| 8 | 600602.SH |
| 9 | 600601.SH |
| 10 | 000005.SZ |
...
I want to sorted the selected data by stock_code(code_id), but I don't want to use join because it takes too much time. Any thoughts?
I tried to use field but it gives me an error, please tell me how to correct it or give me an even better idea.
select * from test
where date = 20050104 and code in (select code from stock_code order by code)
order by field(code, (select code from stock_code order by code));
Error Code: 1242. Subquery returns more than 1 row
You told us that you don't want to join because it takes too much time, but the following join query is probably the best option here:
SELECT t.*
FROM test t
INNER JOIN stock_code sc
ON t.code = sc.code
WHERE t.date = '20050104'
ORDER BY sc.code_id
If this really runs slowly, then you should check to make sure you have indices setup on the appropriate columns. In this case, indices on the code columns from both tables as well as an index on test.date should be very helpful.
ALTER TABLE test ADD INDEX code_idx (code)
ALTER TABLE test ADD INDEX date_idx (date)
ALTER TABLE code ADD INDEX code_idx (code)

Join multiple tables with same column name

I have these tables in my MySQL database:
General table:
+----generalTable-----+
+---------------------+
| id | scenario | ... |
+----+----------+-----+
| 1 | facebook | ... |
| 2 | chief | ... |
| 3 | facebook | ... |
| 4 | chief | ... |
Facebook Table:
+----facebookTable-----+
+----------------------+
| id | expiresAt | ... |
+----+-----------+-----+
| 1 | 12345678 | ... |
| 3 | 45832458 | ... |
Chief Table:
+------chiefTable------+
+----------------------+
| id | expiresAt | ... |
+----+-----------+-----+
| 2 | 43547343 | ... |
| 4 | 23443355 | ... |
Basically, the general table holds some (obviously) general data. Based on the generalTable.scenario you can look up more details in the other two tables, which are in some columns familiar (expiresAt for example) but in others not.
My question is, how to get the joined data of generalTable and the right detailed table in just one query.
So, I would like a query like this:
SELECT id, scenario, expiresAt
FROM generalTable
JOIN facebookTable
ON generalTable.id = facebookTable.id
JOIN chiefTable
ON generalTable.id = chiefTable.id
And an output like this:
| id | scenario | expiresAt |
+----+----------+-----------+
| 1 | facebook | 12345678 |
| 2 | chief | 43547343 |
| 3 | facebook | 45832458 |
| 4 | chief | 23443355 |
However, this doesn't work, because both facebookTable and chiefTable have ambiguous column name "expiresAt". For the ease of use I want to keep it that way. The result table should also only have one column "expiresAt" that is automatically filled with the right values from either facebookTable or chiefTable.
You might want to consider adding expiredAt to your general table, and removing it from the others, to remove duplication in the schema, and to make this particular query simpler.
If you need to stick with your current schema, you can use table aliases to resolve the name ambiguity, and use two joins and a union to create the result you are looking for:
SELECT g.id, g.scenario, f.expiresAt
FROM generalTable g
JOIN facebookTable f
ON g.id = f.id
UNION ALL
SELECT g.id, g.scenario, c.expiresAt
FROM generalTable g
JOIN chiefTable c
ON g.id = c.id;
The outer join approach mentioned in another answer would also solve the problem.
One way you could accomplish it is with LEFT JOIN. In the result fields you can do something like this for common fields IF(fTbl.id IS NULL, cTbl.expiresAt, fTbl.expiresAt) AS expiresAt.

MySQL: Matching records from 2 tables with multiple values

I have 2 tables:
table1
id | title | author | url
1 | the-test | james-brown | www.thetest.com
2 | the-house | clancy-brown | www.thehouse.com
3 | the-desk | leanne-brown | www.thedesk.com
4 | the-head | julie-brown | www.thehead.com
table2
id | title | author | url**
1 | the-mouse | john-blue | www.themouse.com
2 | the-house | clancy-brown | www.thehouse.com
3 | the-cups | carrie-blue | www.thecups.com
4 | the-head | clancy-brown | www.thehead.com
I need results to show only where both title and author match, i.e.
2 | the-house | clancy-brown | www.thehouse.com
I've tried this:
select *
from table1
inner join table2 on (table1.title=table2.title) AND (table1.author=table2.author)
But it just runs forever (there are actually several hundred thousands rows in the real tables).
Just to note, this works fine:
select *
from table1
inner join table2 on (table1.title=table2.title)
I just can't get it to match both tables. Is there a smarter way to do this?
Thanks for all help in advance.
I think your SQL is fine, you just need to index table1 and table2 on author. Add those indices and the JOIN will be fast enough. You also have an issue that you call the column author in your sample data and name in your first query.