Combining data from 2 tables? - mysql

I've been duplicating my data as as noted by the asterisk * below in Snippet 1. This duplication allowed me to run a simple query as such:
"SELECT * FROM tweets ORDER BY time DESC LIMIT 7",
This populates 7 tweets as a default setting.
However, I want to eliminate these redundant columns. To do this I need to pull the other fields from the credentials table.
How would I run a complex query like this? Is this feasible? Is it a good idea?
Snippet 1
Table 1 - tweets (7)
id
h_token
h_file *remove and pull from credentials
picture *remove and pull from credentials
name *remove and pull from credentials
tweet
time
Table 2 - credentials (12)
id
name
email
h_pass
picture
privacy
h_token
h_file
special
page
pane
remember
Each tweet has an h_token associated with it that will be used to add relational data (h_file, name, and picture)

You need to use a join operation, like so:
SELECT tweets.*, credentials.h_file, credentials.picture, credentials.name
FROM tweets JOIN credentials ON tweets.h_token=credentials.h_token
ORDER BY time DESC LIMIT 7;
This is basically your original query, but adding three columns from the credentials table whenever the h_token from the credential and tweets table match up......

Related

Does pymysql's lastrowid function work properly in cases of multiple users inserting into DB?

I have 2 tables in my DB purchase order and lines. Every order can have multiple lines(one line for each part ordered). I am developing an application where an order will first be created. Need to get the ID of this order and then insert lines later on(as the user adds the parts). How can I ensure ther correct value of order ID is fetched?
I cant understand what you exactly want but you should search about ORM its maybe can help you.

Storing 'array' in SQL column and retrieving all rows WHERE certain element is in said array?

I currently have an SQL table listing all the different conversations between the users of a messaging app. This table contains a column titled participantIDs which contains the user ID of each of the (two) parties in the conversation. These values are separated by a comma, for example 19,25 would denote that the conversation was between user 19 and user 25.
Now, I am trying to work out how to retrieve the relevant conversations when a user looks at their messages inbox. To do this, I expect I will need to use a line of code such as
SELECT * FROM `convos` WHERE `participantIDs` LIKE (*contains user id*);
What would be the correct way to write this query?
instead of having one column separated by a coma ,i am suggesting you a simple way, you could create a table called "Personne" with a schema (id, idSender, idRecipient, messages) , and to select all message bbetween perssonne 1 and perssone 2 , you use this request
select messages from Personne where idSender = '1' and idRecipient = '2';
in this way you will respect the first normal form as explicated here Normalization of Database
This is a really, really bad way to do it. As a.slimane says, normalize your database!...
The gist of it is that:
select messages from Personne where idSender = '1' and idRecipient = '2';
...will be fast, since you will create an index on (idSender, idRecipient) which will allow to find the rows with a direct index lookup.
However, there is no way to index a search on "part of a column contains a value". This means MySQL will have to scan many rows (potentially the whole table if you really insist) and it will be terribly slow.
Well, there is one way to index search on "part of a column contains a value": FULLTEXT. But this does not apply here.

Calculation within MYSQL Tables

I have some data in mysql and was wondering whether I can create a new table and then add some type of formula that can count existing tables? For example, I have a table called 'Reviews' which contains 150 rows. Can I have a separate table within mysql that can tell me there are 150 rows without me logging in to see this? Any help appreciated.
You can create a VIEW that contains the count and has other permissions than the table;
CREATE VIEW ReviewCount AS SELECT COUNT(*) FROM Reviews;
This view will have the read access of the defining user, and you can hide the underlying table from the other user, while he can still use the view to get the count.
The thing is, as far as the database is concerned, the other user still has to be logged in. If you want truly anonymous access, you'll have to wrap the database inside your own code, for example a web service.
EDIT: Your comment indicates that what you're looking for is simply a summary table of counts from a number of tables. In that case, you can simply create the view as;
CREATE VIEW test_count AS
SELECT (SELECT COUNT(*) FROM reviews) reviewCount,
(SELECT COUNT(*) FROM records) recordCount,
...
;
An SQLfiddle to test with.

Retrieve SQL objects instead or rows

I have two tables in my database.
Table columns are as follows
************Itinerary*********
USERNAME ITIN
**********Flight Details**********
ITIN FROM TO START_DATE END_DATE START_TIME END_TIME
I would like to retrieve into my server with an SQL query to retrieve multiple objects based on the ITN number. Meaning, my ITIN number has a many to one relationship with the rest of the details. (One ITIN can have many flights and one USERNAME can have many ITIN numbers)
My object on my server side should be like follows:
String username, int ITIN, List flightDetails
I would receive an ITIN for every row I retrieve right now. The one solution I found is to make as many calls to database as there are ITIN numbers for each user. But that results in multiple calls being made.
Other way I thought is to traverse the result set from top to bottom and create a new object for each new ITIN encountered. That results in my looping through all the rows.
Is there a better solution to this problem where I could get one ITIN and USERNAME and multiple rows of flight details so that can be directly inserted into my object?
For one query, you will get back one results. Results are tabular.
Use the ITIN and USERNAME from the first row, and then loop through all rows for the flight details. (I'm not sure what language you are using, so I'll leave this as an exercise for the reader.)
Make sure to a LEFT JOIN if necessary.
select a.username,a.itin from Itinerary a join Flight Details b ON a.itin=b.itin order by a.itin

Mysql Insert data into table have a arranges question?

I found a weard problem with my MySQL DB.
sometime when I insert new data into it, the way it arranges the data is like a stack, for example
4 (newest)
3
2
1 (oldest)
...
how can I make it arranged like this?
1 (newest)
2
3
4 (oldest)
thanks all.
SELECT *
FROM TABLE
ORDER BY ID
You have to remember that when viewing/selecting data from a table without any ORDER BY specified does not garuantee any specific order.
The way you are view the data (unordered) can be due to any one of a lot of factos (the database engine, schema, page storage, page fragmentation, indexes, primary keys, or simply execution plan optimization).
The SQL standards specifically states that tables do not have a "natural" order. Therefore, the database engine is free to return a request without an ORDER BY in any order it wants to. The order may change from one request to another because most engines choose to return the data in whatever order they can get it to you the most rapidly.
It follows, therefore, that if you want the data out in a particular order you must include a column in your table whose job is to proxy for the order in which you added records to the table. Two common ways of doing this are using an autoincrement field which will be in numerical order from oldest to newest record, and a TIMESTAMP column which does just what it says. Once you have such a column you can use ORDER BY ColumnName when searching to get an ordered result set.