I have two tables : This is the clients table.
+--------+---------+--------+------------+--------------+------------+
| id | name | debt | phone | address | products |
+--------+---------+--------+------------+--------------+------------+
| 1 | person1 | 55.54 | 8187654545 | Planet Earth | (none yet) |
| 1 | person2 | 55.64 | 8184256595 | Planet Mars | (none yet) |
+--------+---------+--------+------------+--------------+------------+
This is the products table:
+-----+----------+----------+----------+----------------+-------+
| id | category | name | type | size_in_ounces | price |
+-----+----------+----------+----------+----------------+-------+
| 1 | liquids | product1 | original | 2.7 | 1.99 |
| 1 | liquids | product2 | original | 7.7 | 5.99 |
| 1 | liquids | product3 | original | 10 | 7.99 |
+-----+----------+----------+----------+----------------+-------+
I am trying to add the name column from a row in the products table into the products column in the clients table. Basically what I am trying to accomplish is, on query, this to show in the clients table, and if possible for the clients debt column to increase in price accordingly.
+--------+---------+--------+------------+--------------+------------+
| id | name | debt | phone | address | products |
+--------+---------+--------+------------+--------------+------------+
| 1 | person1 | 63.49 | 8187654545 | Planet Earth | product3 |
| 1 | person2 | 57.63 | 8184256595 | Planet Mars | product1 |
+--------+---------+--------+------------+--------------+------------+
I tried to do this: but SQL gives me an error. I know the following code is wrong but it can give you an idea of what I'm trying to accomplish.
INSERT INTO `clients` (products) WHERE `name` = "person1"
SELECT `name` FROM `products` WHERE `name` = "product3";
And here is another silly thing; if I do this code :
INSERT INTO `clients` (products)
SELECT `name` FROM `products` WHERE `name` = "product3";
It creates a completely new client with every column null or empty except for the products column where it adds product3. Weird right?
Related
I have the following MySQL table which is structured like that:
| id | bonus0 |
Now I want to add the following data set:
| id | bonus0 | bonus1 | bonus2 | bonus3 |
| 10 | 4582 | 2552 | 8945 | 7564 |
As you can see the columns bonus1 - bonus3 aren´t created yet.
How would a php script/ query look like which checks if enough columns are already available and if not which will create the missing ones with consecutive numbers at the end of the word "bonus"?
So in the example the columns bonus1 - bonus3 would be created automatically by the script.
In reality (I mean a normalized relational database) you should have 3 tables. Lets call them people, bonuses and bonus_to_person
people looks like:
+-----------------+------------+
| person_id | name |
+_________________+____________+
| 1 | john |
+-----------------+------------+
| 2 | frank |
+-----------------+------------+
bonuses Looks like
+----------------+--------------+
| bonus_id | amount |
+________________+______________+
| 1 | 1000 |
+----------------+--------------+
| 2 | 1150 |
+----------------+--------------+
| 3 | 1200 |
+----------------+--------------+
| 4 | 900 |
+----------------+--------------+
| 5 | 150 |
+----------------+--------------+
| 6 | 200 |
+----------------+--------------+
bonus_to_person Looks like
+----------------+-----------------+
| bonus_id | person_id |
+________________+_________________+
| 1 | 1 |
+----------------+-----------------+
| 2 | 2 |
+----------------+-----------------+
| 3 | 2 |
+----------------+-----------------+
| 4 | 1 |
+----------------+-----------------+
| 5 | 1 |
+----------------+-----------------+
| 6 | 1 |
+----------------+-----------------+
This way, any ONE person can have unlimited bonuses simply by INSERTING into bonuses with the amount, and INSERTING into bonus_to_person with the bonus_id and person_id
The retrieval of this data would look like
SELECT a.name, c.amount from people a
LEFT JOIN bonus_to_people b
ON a.person_id = b.person_id
LEFT JOIN bonuses c
ON c.bonus_id = b.bonus_id
WHERE a.person.id = 1;
Your result from something like this would look like
+------------+----+-------+
| name | amount |
+____________+____________+
| john | 1000 |
+------------+------------+
| john | 900 |
+------------+------------+
| john | 150 |
+------------+------------+
| john | 200 |
+------------+------------+
You should be using this normalized approach for any database that will continue growing -- Growing "deeper" than "wider" is better in your case ..
// Get existing columns of the table
// $queryResult = run SQL query using PDO/mysqli/your favorite thing: SHOW COLUMNS FROM `table`
// Specify wanted columns
$search = ['bonus0', 'bonus1', 'bonus2', 'bonus3'];
// Get just the field names from the resultset
$fields = array_column($queryResult, 'Field');
// Find what's missing
$missing = array_diff($search, $fields);
// Add missing columns to the table
foreach ($missing as $field) {
// Run SQL query: ALTER TABLE `table` ADD COLUMN $field INT
}
I have four tables that I need to join together, with one of those tables having two different records I need to grab. The guild and party tables I'm getting the name of those so that I can display the name instead of ID to the user, and the charlog table has the char_id's creation date and last login date that I want to show as well. Here are the tables:
char table:
----------------------------------------------------
| char_id | name | guild_id | party_id |
|---------------------------------------------------
| 150000 | char1 | 3 | 3 |
| 150001 | char2 | 2 | (NULL) |
| 150002 | char3 | (NULL) | 1 |
| 150003 | char4 | 1 | 2 |
----------------------------------------------------
guild table:
-------------------------
| guild_id | name |
-------------------------
| 1 | guild_1 |
| 2 | guild_2 |
| 3 | guild_3 |
-------------------------
party table:
-------------------------
| party_id | name |
-------------------------
| 1 | party_1 |
| 2 | party_2 |
| 3 | party_3 |
-------------------------
charlog table:
----------------------------------------------------
| time | char_id | char_msg |
----------------------------------------------------
| 2015-02-14 06:45:32 | 150000 | make new char |
| 2015-02-14 06:45:58 | 150000 | char select |
| 2015-02-15 12:32:19 | 150001 | make new char |
| 2015-02-15 16:54:01 | 150000 | char select |
| 2015-02-15 19:23:54 | 150001 | char select |
| 2015-02-16 01:32:13 | 150002 | make new char |
| 2015-02-16 01:33:01 | 150003 | make new char |
| 2015-02-16 04:45:43 | 150000 | char select |
| 2015-02-16 07:43:22 | 150003 | char select |
----------------------------------------------------
As mentioned, I need to get the make new char entry from the charlog table to display when the character was created and as well the LAST (by date) char select entry to display when the character was played, all of this with one single char_id.
All in all, I'd be looking for a table that looks like this:
---------------------------------------------------------------------------------------------------------------------
| char_id | name | guild_id | guild_name | party_id | party_name | create_time | lastlogin_time |
---------------------------------------------------------------------------------------------------------------------
| 150000 | char1 | 3 | guild_3 | 3 | party_3 | 2015-02-14 06:45:32 | 2015-02-16 04:45:43 |
I'm using the following active record lines in Codeigniter to attempt to get the data I need. It returns the create_date correctly but the lastlogin_time is not returned (it's blank):
function get_char_info($cid) {
$this->db->select('char.*,guild.guild_id,guild.name AS guild_name,party.party_id,party.name AS party_name,charlog1.time AS create_time,charlog2.time AS lastlogin_time');
$this->db->from('char');
$this->db->where('char.char_id', $cid);
$this->db->join('guild', 'char.guild_id = guild.guild_id', 'left');
$this->db->join('party', 'char.party_id = party.party_id', 'left');
$this->db->join('charlog AS charlog1', 'char.char_id = charlog1.char_id AND charlog1.char_msg = "make new char"', 'left');
$this->db->join('charlog AS charlog2', 'char.char_id = charlog2.char_id AND charlog2.char_msg = (SELECT max(charlog.time) FROM charlog WHERE char_msg = "char select")', 'left');
$query = $this->db->get();
return $query->row();
}
As mentioned, the guild_name, party_name and create_time come through correctly, but the lastlogin_time is blank, no error.
I've tried jumbling some things around in the active record clauses but can't get the lastlogin_time to show. Any help would be appreciated.
The join on your subquery is not correct :
It should be charlog2.time = (SELECT....) not charlog2.char_msg = (SELECT....)
I have 2 tables, the 'department' and 'document'.
Table department
| doc_id | dept_name |
----------------------------------
| 1 | Information Technology|
| 2 | Software Development |
| 3 | Human Resource |
| 4 | Accounting |
| 5 | Support |
Table document
| doc_id | doc_name | author | description | department |
----------------------------------------------------------------------------
| 1 | Maps | User1 | sample | Information Technology |
| 2 | Audits | User3 | sample | Software Development |
| 3 | Image | User1 | sample | Information Technology |
| 4 | Papers | User4 | sample | Human Resource |
| 5 | Print Screen| User1 | sample | Software Development |
| 6 | Transaction | User3 | sample | Accounting |
| 7 | Graph | User1 | sample | Support |
| 8 | Excel | User1 | sample | Information Technology |
Now, I want to display the table with two columns: department and total_doc.
Output:
| department |total_doc|
-----------------------------------
| Information Technology| 3 |
| Software Development | 2 |
| Human Resource | 1 |
| Accounting | 1 |
| Support | 1 |
I want to display the total document inside the department and arrange them in ascending order.
Here's my query.(not sure)
SELECT department, count(doc_name) as 'total_doc' FROM tbl_document GROUP BY doc_name
I'm using MVC pattern in Codeigniter.
$this->db->select("department, count(doc_name) as 'total_doc'");
$this->db->from('document');
$this->db->group_by('doc_name');
Also, How can I display this in table? like using foreach in html?
You need to do group by with department not with doc_name.
$this->db->select("department, count(doc_name) as 'total_doc'");
$this->db->from('document');
$this->db->group_by('department');
$result = $this->db->get()->result();
Hope This will help you.
foreach ($result as $row)
{
echo $row->department."----".$row->total_doc;
}
here you go
SELECT dept_name,COUNT(td.department) FROM department d
LEFT JOIN tdocument td ON td.`department`=d.`dept_name`
GROUP BY td.`department` ORDER BY COUNT(td.`department`) DESC;
You want one line per department. IN SQL words: You want to group by department.
select department, count(*) as total_doc from document group by department;
(BTW: don't use single quotes for column aliases.)
I am creating a search portal in PHP from which user can search for a specific cuisine. In MySQL I have multiple tables for each cuisine and the respective hotel names that offer the cuisine. For example, in table
How can I query a specific cuisine table based on the cuisine search keyword?
So if a user enters 'mexican' as the search query, how can it connect to the 'Table2 - Mexican' and return the hotel names from this table?
Table1 - Chinese
_______________________
| id | hotelname |
|______|______________|
| 1 | hotel1 |
| 2 | hotel2 |
| 3 | hotel3 |
| 4 | hotel4 |
| 5 | hotel5 |
|______|______________|
Table2 - Mexican
_______________________
| id | hotelname |
|______|______________|
| 1 | hotel1 |
| 2 | hotel2 |
| 3 | hotel3 |
| 4 | hotel4 |
| 5 | hotel5 |
|______|______________|
Table3 - Pizza
_______________________
| id | hotelname |
|______|______________|
| 1 | hotel1 |
| 2 | hotel2 |
| 3 | hotel3 |
| 4 | hotel4 |
| 5 | hotel5 |
|______|______________|
Your database concept is very unflexible. I think you should put the cuisines into your database as information (i.e. table content) instead of metadata describing single tables. Tables should generally considered to be static just like the code you write to access the database and its tables. If you implement the cuisines as different tables you would have to hardwire every cuisine into your code.
Here is a suggestion for a better approach:
Create a hotels table to store all the hotels,
Create a cuisines table to store all the different types of cuisines,
Make an additional table to establish the n:m relationship between the hotel and the cuisine.
Example:
hotels: id, name, address, city, telno, email
cuisine: id, name, description
rel: cuisine, hotel (where both are the foreign keys to the
id columns of the respective tables above)
See also:
How to handle a Many-to-Many relationship with PHP and MySQL.
MySQL: Many To Many Relationships » Return True
You might want to check this question to create a many-to-many relationship:
many-to-many and many-to-many intersections
I guess what you would like to achieve is something like this:
Table1 - Hotel
_______________________
| id | hotelname |
|______|______________|
| 1 | hotel1 |
| 2 | hotel2 |
| 3 | hotel3 |
| 4 | hotel4 |
| 5 | hotel5 |
|______|______________|
Table2 - Cuisine
____________________________________________
| id | cuisine_name | keywords |
|______|______________|____________________|
| 1 | Chinese | Shandong,Noodles,. |
| 2 | Mexican | Tacos,Beans,... |
| 3 | Itarian | Pizza,Pasta,.. |
|______|______________|____________________|
Table3 - HotelCuisine
___________________________________
| id | hotel_id | cuisine_id |
|______|____________|______________
| 1 | 1 | 2 |
| 2 | 1 | 3 |
| 3 | 2 | 1 |
| 4 | 2 | 2 |
| 5 | 3 | 3 |
|______|____________|_____________|
SQL:
SELECT hotelname, cuisine_name FROM Hotel
INNER JOIN HotelCuisine ON Hotel.id = HotelCuisine.hotel_id
INNER JOIN Cuisine ON Cuisine.id = HotelCuisine.cuisine_id
WHERE keywords like '%pizza%'
Result:
________________________________________
| hotelname | cuisine_name |
|_______________|______________________|
| hotel1 | Itarian |
| hotel3 | Itarian |
|_______________|______________________|
DEMO: http://sqlfiddle.com/#!2/961de/1
Hope this helps
you can check SQL UNION. But instead of having multiple tables with the same fields, you can try normalization to minimize the redundancy and to make queries easier.
Something like:
Hotel Table
-----------------------------
id | hotelname | categoryID
------------------------------
1 | hotel name 1 | 1
2 | hotel name 2 | 2
-----------------------------
Category Table
-------------------
id | categoryname
-------------------
1 | chinese
2 | mexican
------------------
And query as simple as:
SELECT a.hotelname, b,categoryname
FROM hotel_table a
LEFT JOIN category_table b
ON a.categoryID = b.id AND b.categoryname LIKE '%mexican%';
I have three tables: years, employees, positions. Suppose that I already have these data in those tables.
years:
----------------
| id | name |
----------------
| 1 | 2011 |
----------------
positions:
------------------------------
| id | name | year_id |
------------------------------
| 1 | Director | 1 |
| 2 | Manager | 1 |
------------------------------
employees:
---------------------------------------------------------
| id | name | position_id | year_id |
---------------------------------------------------------
| 1 | Employee A (Director) | 1 | 1 |
| 2 | Employee B (Manager) | 2 | 1 |
---------------------------------------------------------
========================================
The years table is a central point.
If I insert a new year record, I must also copy all positions and employees which are related to the previous year.
So if I insert year 2012 into the years table, the data is suppose to be like this:
years:
----------------
| id | name |
----------------
| 1 | 2011 |
| 2 | 2012 |
----------------
positions:
------------------------------
| id | name | year_id |
------------------------------
| 1 | Director | 1 |
| 2 | Manager | 1 |
| 3 | Director | 2 |
| 4 | Manager | 2 |
------------------------------
employees:
---------------------------------------------------------
| id | name | position_id | year_id |
---------------------------------------------------------
| 1 | Employee A (Director) | 1 | 1 |
| 2 | Employee B (Manager) | 2 | 1 |
| 3 | Employee A (Director) | 3 (?) | 2 |
| 4 | Employee B (Manager) | 4 (?) | 2 |
---------------------------------------------------------
NOTICE the question marks in the third and fourth row of employees table.
I use these queries to insert a new year and copy all related positions and employees:
// Insert new year record
INSERT INTO years (name) VALUES (2012);
// Get last inserted year ID
$inserted_year_id = .......... // skipped
// Copy positions
INSERT INTO positions (name, year_id) SELECT name, $inserted_year_id AS last_year_id FROM positions WHERE year_id = 1;
// Copy employees
INSERT INTO employees (name, position_id, year_id) SELECT name, position_id, $inserted_year_id AS last_year_id FROM employees WHERE year_id = 1;
The problem is at copying employees query. I can't find a method to get or track the new ID of positions.
Is there a simple method to do this?
Thank you very much.
Your data model is seriously flawed and probably needs a complete overhaul, but if you insist on copying the data like you describe, this should do the trick:
// Copy employees
INSERT INTO employees (name, position_id, year_id)
SELECT name, new_positions.id, $inserted_year_id AS last_year_id
FROM employees
JOIN positions AS old_positions ON old_positions.id = employees.position_id
AND old_positions.year_id = employees.year_id
JOIN positions AS new_positions ON new_positions.name = old_positions.name
AND new_positions.year_id = $inserted_year_id
WHERE employees.year_id = 1
I think you should read about database normalization. Copying the data leads to maintenance issues and erroneous reporting.
If you went with a different design like the following, then there would be nothing to insert, until an employee changes position, is terminated, or a position is discontinued. There are plenty of other ways to approach this, too, but you should minimize redundancy (i.e. have only one copy of each Employee), and then keep track of data that changes over time, separately. Also read about foreign keys before you try to implement something like this.
positions:
-- If you are keeping track of the years that each position is active,
-- using dates provides simplicity. Note: this design assumes that positions
-- are never reactivated after being deactivated.
------------------------------------------------
| id | name | DateActive | DateInactive |
------------------------------------------------
| 1 | Director | 01/01/2011 | |
| 2 | Manager | 01/01/2011 | |
------------------------------------------------
employees:
---------------------------------------------------------------
| id | name | DateHired | DateTerminated |
---------------------------------------------------------------
| 1 | Employee A | 01/01/2011 | |
| 2 | Employee B | 01/01/2011 | |
| 3 | Employee C | 01/01/2011 | 10/01/2012 |
---------------------------------------------------------------
EmployeePositionRelationships
--If you are keeping track of time that each employee held a position
-- Employee A has been a Director since 1/1/2011
-- Employee B was a Manager from 1/1/2011 to 10/6/2012. Then they became a Director
-- Employee B was a Manager from 1/1/2011 to 10/1/2012. Then they were terminated
--------------------------------------------------------
EmployeeId | PositionId | DateStarted | DateEnded |
--------------------------------------------------------
1 | 1 | 01/01/2011 | |
2 | 2 | 01/01/2011 | 10/6/2012 |
3 | 2 | 01/01/2011 | 10/1/2012 |
2 | 1 | 10/6/2012 | |
--------------------------------------------------------